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 # Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available. # settings weren't available.
if self._request_middleware is None: if self._request_middleware is None:
self.initLock.acquire() with self.initLock:
try:
try: try:
# Check that middleware is still uninitialised. # Check that middleware is still uninitialised.
if self._request_middleware is None: if self._request_middleware is None:
@ -220,8 +219,6 @@ class WSGIHandler(base.BaseHandler):
# Unload whatever middleware we got # Unload whatever middleware we got
self._request_middleware = None self._request_middleware = None
raise raise
finally:
self.initLock.release()
set_script_prefix(base.get_script_name(environ)) set_script_prefix(base.get_script_name(environ))
signals.request_started.send(sender=self.__class__) 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.""" """Write all messages to the stream in a thread-safe way."""
if not email_messages: if not email_messages:
return return
self._lock.acquire() with self._lock:
try: try:
stream_created = self.open() stream_created = self.open()
for message in email_messages: for message in email_messages:
self.stream.write('%s\n' % message.message().as_string()) self.stream.write('%s\n' % message.message().as_string())
self.stream.write('-'*79) self.stream.write('-'*79)
self.stream.write('\n') self.stream.write('\n')
self.stream.flush() # flush after each message self.stream.flush() # flush after each message
if stream_created: if stream_created:
self.close() self.close()
except: except:
if not self.fail_silently: if not self.fail_silently:
raise raise
finally:
self._lock.release()
return len(email_messages) return len(email_messages)

View File

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

View File

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

View File

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

View File

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