Switch to using context managers for acquiring and releasing locks.

This commit is contained in:
Alex Gaynor 2012-06-23 08:11:15 -07:00
parent e1b74d0094
commit e0fce8706d
6 changed files with 28 additions and 57 deletions

View File

@ -210,8 +210,7 @@ class WSGIHandler(base.BaseHandler):
# Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available.
if self._request_middleware is None:
self.initLock.acquire()
try:
with self.initLock:
try:
# Check that middleware is still uninitialised.
if self._request_middleware is None:
@ -220,8 +219,6 @@ class WSGIHandler(base.BaseHandler):
# Unload whatever middleware we got
self._request_middleware = None
raise
finally:
self.initLock.release()
set_script_prefix(base.get_script_name(environ))
signals.request_started.send(sender=self.__class__)

View File

@ -16,19 +16,17 @@ class EmailBackend(BaseEmailBackend):
"""Write all messages to the stream in a thread-safe way."""
if not email_messages:
return
self._lock.acquire()
try:
stream_created = self.open()
for message in email_messages:
self.stream.write('%s\n' % message.message().as_string())
self.stream.write('-'*79)
self.stream.write('\n')
self.stream.flush() # flush after each message
if stream_created:
self.close()
except:
if not self.fail_silently:
raise
finally:
self._lock.release()
with self._lock:
try:
stream_created = self.open()
for message in email_messages:
self.stream.write('%s\n' % message.message().as_string())
self.stream.write('-'*79)
self.stream.write('\n')
self.stream.flush() # flush after each message
if stream_created:
self.close()
except:
if not self.fail_silently:
raise
return len(email_messages)

View File

@ -80,8 +80,7 @@ class EmailBackend(BaseEmailBackend):
"""
if not email_messages:
return
self._lock.acquire()
try:
with self._lock:
new_conn_created = self.open()
if not self.connection:
# We failed silently on open().
@ -94,8 +93,6 @@ class EmailBackend(BaseEmailBackend):
num_sent += 1
if new_conn_created:
self.close()
finally:
self._lock.release()
return num_sent
def _send(self, email_message):

View File

@ -54,8 +54,7 @@ class AppCache(object):
"""
if self.loaded:
return
self.write_lock.acquire()
try:
with self.write_lock:
if self.loaded:
return
for app_name in settings.INSTALLED_APPS:
@ -66,8 +65,6 @@ class AppCache(object):
for app_name in self.postponed:
self.load_app(app_name)
self.loaded = True
finally:
self.write_lock.release()
def _label_for(self, app_mod):
"""
@ -138,8 +135,7 @@ class AppCache(object):
the app has no models in it and 'emptyOK' is True, returns None.
"""
self._populate()
self.write_lock.acquire()
try:
with self.write_lock:
for app_name in settings.INSTALLED_APPS:
if app_label == app_name.split('.')[-1]:
mod = self.load_app(app_name, False)
@ -150,8 +146,6 @@ class AppCache(object):
else:
return mod
raise ImproperlyConfigured("App with label %s could not be found" % app_label)
finally:
self.write_lock.release()
def get_app_errors(self):
"Returns the map of known problems with the INSTALLED_APPS."

View File

@ -99,15 +99,12 @@ class Signal(object):
if weak:
receiver = saferef.safeRef(receiver, onDelete=self._remove_receiver)
self.lock.acquire()
try:
with self.lock:
for r_key, _ in self.receivers:
if r_key == lookup_key:
break
else:
self.receivers.append((lookup_key, receiver))
finally:
self.lock.release()
def disconnect(self, receiver=None, sender=None, weak=True, dispatch_uid=None):
"""
@ -136,15 +133,12 @@ class Signal(object):
else:
lookup_key = (_make_id(receiver), _make_id(sender))
self.lock.acquire()
try:
with self.lock:
for index in xrange(len(self.receivers)):
(r_key, _) = self.receivers[index]
if r_key == lookup_key:
del self.receivers[index]
break
finally:
self.lock.release()
def send(self, sender, **named):
"""
@ -237,8 +231,7 @@ class Signal(object):
Remove dead receivers from connections.
"""
self.lock.acquire()
try:
with self.lock:
to_remove = []
for key, connected_receiver in self.receivers:
if connected_receiver == receiver:
@ -250,8 +243,6 @@ class Signal(object):
for idx, (r_key, _) in enumerate(reversed(self.receivers)):
if r_key == key:
del self.receivers[last_idx-idx]
finally:
self.lock.release()
def receiver(signal, **kwargs):

View File

@ -603,21 +603,16 @@ class FakeSMTPServer(smtpd.SMTPServer, threading.Thread):
maddr = email.Utils.parseaddr(m.get('from'))[1]
if mailfrom != maddr:
return "553 '%s' != '%s'" % (mailfrom, maddr)
self.sink_lock.acquire()
self._sink.append(m)
self.sink_lock.release()
with self.sink_lock:
self._sink.append(m)
def get_sink(self):
self.sink_lock.acquire()
try:
with self.sink_lock:
return self._sink[:]
finally:
self.sink_lock.release()
def flush_sink(self):
self.sink_lock.acquire()
self._sink[:] = []
self.sink_lock.release()
with self.sink_lock:
self._sink[:] = []
def start(self):
assert not self.active
@ -629,9 +624,8 @@ class FakeSMTPServer(smtpd.SMTPServer, threading.Thread):
self.active = True
self.__flag.set()
while self.active and asyncore.socket_map:
self.active_lock.acquire()
asyncore.loop(timeout=0.1, count=1)
self.active_lock.release()
with self.active_lock:
asyncore.loop(timeout=0.1, count=1)
asyncore.close_all()
def stop(self):