Skip to content

Commit 9ee6ea4

Browse files
committed
Use context managers where reasonable
1 parent 261e21a commit 9ee6ea4

File tree

8 files changed

+100
-96
lines changed

8 files changed

+100
-96
lines changed

webware/Application.py

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,7 @@ def __init__(self, path=None, settings=None, development=None):
220220
if filename:
221221
if '/' not in filename:
222222
filename = os.path.join(self._logDir, filename)
223+
# pylint: disable=consider-using-with
223224
sys.stderr = sys.stdout = open(filename, 'a', buffering=1)
224225

225226
self.initErrorPage()
@@ -609,31 +610,29 @@ def writeActivityLog(self, trans):
609610
if '/' not in filename:
610611
filename = os.path.join(self._logDir, filename)
611612
filename = self.serverSidePath(filename)
612-
if os.path.exists(filename):
613-
f = open(filename, 'a')
614-
else:
615-
f = open(filename, 'w')
616-
f.write(','.join(self.setting('ActivityLogColumns')) + '\n')
617-
values = []
618-
objects = dict(
619-
application=self, transaction=trans,
620-
request=trans.request(), response=trans.response(),
621-
servlet=trans.servlet(),
622-
# don't cause creation of session here:
623-
session=trans._session)
624-
for column in self.setting('ActivityLogColumns'):
625-
try:
626-
value = valueForName(objects, column)
627-
except Exception:
628-
value = '(unknown)'
629-
if isinstance(value, float):
630-
# probably need more flexibility in the future
631-
value = f'{value:02f}'
632-
else:
633-
value = str(value)
634-
values.append(value)
635-
f.write(','.join(values) + '\n')
636-
f.close()
613+
mode = 'a' if os.path.exists(filename) else 'w'
614+
with open(filename, mode) as f:
615+
if mode == 'w':
616+
f.write(','.join(self.setting('ActivityLogColumns')) + '\n')
617+
values = []
618+
objects = dict(
619+
application=self, transaction=trans,
620+
request=trans.request(), response=trans.response(),
621+
servlet=trans.servlet(),
622+
# don't cause creation of session here:
623+
session=trans._session)
624+
for column in self.setting('ActivityLogColumns'):
625+
try:
626+
value = valueForName(objects, column)
627+
except Exception:
628+
value = '(unknown)'
629+
if isinstance(value, float):
630+
# probably need more flexibility in the future
631+
value = f'{value:02f}'
632+
else:
633+
value = str(value)
634+
values.append(value)
635+
f.write(','.join(values) + '\n')
637636

638637
def startTime(self):
639638
"""Return the time the application was started.

webware/MiscUtils/ParamFactory.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,12 @@ def __init__(self, klass, **extraMethods):
1616
setattr(self, name, func)
1717

1818
def __call__(self, *args):
19-
self.lock.acquire()
20-
if args in self.cache:
21-
self.lock.release()
22-
return self.cache[args]
23-
value = self.klass(*args)
24-
self.cache[args] = value
25-
self.lock.release()
19+
with self.lock:
20+
if args in self.cache:
21+
value = self.cache[args]
22+
else:
23+
value = self.klass(*args)
24+
self.cache[args] = value
2625
return value
2726

2827
def allInstances(self):

webware/MiscUtils/PickleCache.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ def read(self, filename,
107107
try:
108108
if v:
109109
print(f'About to open for read {picklePath!r}.')
110+
# pylint: disable=consider-using-with
110111
file = open(picklePath, 'rb')
111112
except IOError as e:
112113
if v:
@@ -209,7 +210,8 @@ def write(self, data, filename,
209210
pprint(d)
210211
try:
211212
if v:
212-
print('About to open for write %r.' % picklePath)
213+
print(f'About to open for write {picklePath!r}.')
214+
# pylint: disable=consider-using-with
213215
pickleFile = open(picklePath, 'wb')
214216
except IOError as e:
215217
if v:
@@ -225,6 +227,7 @@ def write(self, data, filename,
225227
print('Timestamps are identical, sleeping'
226228
f' {self._writeSleepInterval:%0.2f} seconds.')
227229
sleep(self._writeSleepInterval)
230+
# pylint: disable=consider-using-with
228231
pickleFile = open(picklePath, 'wb')
229232
else:
230233
break

webware/ServletFactory.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -305,14 +305,13 @@ def flushCache(self):
305305
Servlets that are currently in the wild may find their way back
306306
into the cache (this may be a problem).
307307
"""
308-
self._importLock.acquire()
309-
self._classCache = {}
310-
# We can't just delete all the lists, because returning
311-
# servlets expect it to exist.
312-
for key in self._servletPool:
313-
self._servletPool[key] = []
314-
self._threadsafeServletCache = {}
315-
self._importLock.release()
308+
with self._importLock:
309+
self._classCache = {}
310+
# We can't just delete all the lists, because returning
311+
# servlets expect it to exist.
312+
for key in self._servletPool:
313+
self._servletPool[key] = []
314+
self._threadsafeServletCache = {}
316315

317316
# endregion Servlet Pool
318317

webware/SessionFileStore.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ def __getitem__(self, key):
4646
filename = self.filenameForKey(key)
4747
with self._lock:
4848
try:
49+
# pylint: disable=consider-using-with
4950
sessionFile = open(filename, 'rb')
5051
except IOError as e:
5152
raise KeyError(key) from e # session file not found
@@ -73,6 +74,7 @@ def __setitem__(self, key, value):
7374
if dirty:
7475
value.setDirty(False)
7576
try:
77+
# pylint: disable=consider-using-with
7678
sessionFile = open(filename, 'wb')
7779
try:
7880
try:

webware/Tests/TestEndToEnd/TestExamples.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,15 @@ def setUp(self):
2020
@staticmethod
2121
def removeDemoDatabase():
2222
# pylint: disable=unused-variable
23-
for i in range(20):
23+
for i in range(40):
2424
if not os.path.exists('demo.db'):
2525
break
2626
try:
2727
os.remove('demo.db')
2828
except OSError:
2929
sleep(.5)
3030
else:
31+
sleep(.5)
3132
break
3233

3334
def testStartPage(self):

webware/Tests/TestEndToEnd/TestServer.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ def tearDownClass(cls):
168168
chdir(cls.currentDir)
169169

170170
def getPage(self, path=''):
171+
# pylint: disable=consider-using-with
171172
return urlopen(f'http://localhost:8080/{path}')
172173

173174
def compareOutput(self, gotLines, expectedLines):

webware/UnknownFileTypeServlet.py

Lines changed: 54 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -188,64 +188,64 @@ def serveContent(self, trans):
188188

189189
filename = self.filename(trans)
190190
try:
191+
# pylint: disable=consider-using-with
191192
f = open(filename, 'rb')
192193
except IOError as e:
193194
raise HTTPExceptions.HTTPNotFound from e
194-
195-
stat = os.fstat(f.fileno())
196-
fileSize, mtime = stat[6], stat[8]
197-
198-
if debug:
199-
print('>> UnknownFileType.serveContent()')
200-
print('>> filename =', filename)
201-
print('>> size=', fileSize)
202-
fileDict = fileCache.get(filename)
203-
if fileDict is not None and mtime != fileDict['mtime']:
204-
# Cache is out of date; clear it.
205-
if debug:
206-
print('>> changed, clearing cache')
207-
del fileCache[filename]
208-
fileDict = None
209-
if fileDict is None:
195+
try:
196+
stat = os.fstat(f.fileno())
197+
fileSize, mtime = stat[6], stat[8]
210198
if debug:
211-
print('>> not found in cache')
212-
mimeType, mimeEncoding = guess_type(filename, False)
213-
if mimeType is None:
214-
mimeType, mimeEncoding = 'application/octet-stream', None
215-
else:
216-
mimeType = fileDict['mimeType']
217-
mimeEncoding = fileDict['mimeEncoding']
218-
response.setHeader('Content-Type', mimeType)
219-
response.setHeader('Content-Length', str(fileSize))
220-
if mimeEncoding:
221-
response.setHeader('Content-Encoding', mimeEncoding)
222-
if trans.request().method() == 'HEAD':
199+
print('>> UnknownFileType.serveContent()')
200+
print('>> filename =', filename)
201+
print('>> size=', fileSize)
202+
fileDict = fileCache.get(filename)
203+
if fileDict is not None and mtime != fileDict['mtime']:
204+
# Cache is out of date; clear it.
205+
if debug:
206+
print('>> changed, clearing cache')
207+
del fileCache[filename]
208+
fileDict = None
209+
if fileDict is None:
210+
if debug:
211+
print('>> not found in cache')
212+
mimeType, mimeEncoding = guess_type(filename, False)
213+
if mimeType is None:
214+
mimeType, mimeEncoding = 'application/octet-stream', None
215+
else:
216+
mimeType = fileDict['mimeType']
217+
mimeEncoding = fileDict['mimeEncoding']
218+
response.setHeader('Content-Type', mimeType)
219+
response.setHeader('Content-Length', str(fileSize))
220+
if mimeEncoding:
221+
response.setHeader('Content-Encoding', mimeEncoding)
222+
if trans.request().method() == 'HEAD':
223+
return
224+
if (fileDict is None and self.setting('ReuseServlets')
225+
and self.shouldCacheContent()
226+
and fileSize < maxCacheContentSize):
227+
if debug:
228+
print('>> caching')
229+
fileDict = dict(
230+
content=f.read(),
231+
mimeType=mimeType, mimeEncoding=mimeEncoding,
232+
mtime=mtime, size=fileSize, filename=filename)
233+
fileCache[filename] = fileDict
234+
if fileDict is not None:
235+
if debug:
236+
print('>> sending content from cache')
237+
response.write(fileDict['content'])
238+
else: # too big or not supposed to cache
239+
if debug:
240+
print('>> sending directly')
241+
numBytesSent = 0
242+
while numBytesSent < fileSize:
243+
data = f.read(min(fileSize-numBytesSent, readBufferSize))
244+
if data == '':
245+
break # unlikely, but safety first
246+
response.write(data)
247+
numBytesSent += len(data)
248+
finally:
223249
f.close()
224-
return
225-
if (fileDict is None and self.setting('ReuseServlets')
226-
and self.shouldCacheContent()
227-
and fileSize < maxCacheContentSize):
228-
if debug:
229-
print('>> caching')
230-
fileDict = dict(
231-
content=f.read(),
232-
mimeType=mimeType, mimeEncoding=mimeEncoding,
233-
mtime=mtime, size=fileSize, filename=filename)
234-
fileCache[filename] = fileDict
235-
if fileDict is not None:
236-
if debug:
237-
print('>> sending content from cache')
238-
response.write(fileDict['content'])
239-
else: # too big or not supposed to cache
240-
if debug:
241-
print('>> sending directly')
242-
numBytesSent = 0
243-
while numBytesSent < fileSize:
244-
data = f.read(min(fileSize-numBytesSent, readBufferSize))
245-
if data == '':
246-
break # unlikely, but safety first
247-
response.write(data)
248-
numBytesSent += len(data)
249-
f.close()
250250

251251
# endregion Init et al

0 commit comments

Comments
 (0)