Ticket #8616: cross_platform_session_file_read_write_locking.diff
File cross_platform_session_file_read_write_locking.diff, 2.7 KB (added by , 16 years ago) |
---|
-
django/contrib/sessions/backends/file.py
5 5 from django.conf import settings 6 6 from django.contrib.sessions.backends.base import SessionBase, CreateError 7 7 from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured 8 from django.core.files import locks 8 9 10 IO_LOCK_SUFFIX = "_iolock" 9 11 10 12 class SessionStore(SessionBase): 11 13 """ … … 42 44 43 45 return os.path.join(self.storage_path, self.file_prefix + session_key) 44 46 47 def _key_to_io_lock_file(self, session_key=None): 48 """ 49 Get the I/O lock file associated with this session key. 50 """ 51 return self._key_to_file(session_key) + IO_LOCK_SUFFIX 52 45 53 def load(self): 46 54 session_data = {} 47 55 try: 56 # Open and acquire a shared lock on the I/O lock file before 57 # attempting to read the session file. This makes us wait to read 58 # the session file until another thread or process is finished 59 # writing it. 60 io_lock_file = open(self._key_to_io_lock_file(), "rb") 61 locks.lock(io_lock_file, locks.LOCK_SH) 62 48 63 session_file = open(self._key_to_file(), "rb") 49 64 try: 50 65 try: … … 53 68 self.create() 54 69 finally: 55 70 session_file.close() 71 io_lock_file.close() 56 72 except IOError: 57 73 pass 58 74 return session_data … … 76 92 # truncating the file to save. 77 93 session_data = self._get_session(no_load=must_create) 78 94 try: 95 # Open and acquire an exclusive lock on the I/O lock file before 96 # attempting to write the session file. This makes other threads 97 # or processes wait to read or write the session file until we are 98 # finished writing it. 99 io_lock_file = open(self._key_to_io_lock_file(), "wb") 100 locks.lock(io_lock_file, locks.LOCK_EX) 101 79 102 fd = os.open(self._key_to_file(self.session_key), flags) 80 103 try: 81 104 os.write(fd, self.encode(session_data)) 82 105 finally: 83 106 os.close(fd) 107 io_lock_file.close() 84 108 except OSError, e: 85 109 if must_create and e.errno == errno.EEXIST: 86 110 raise CreateError … … 100 124 session_key = self._session_key 101 125 try: 102 126 os.unlink(self._key_to_file(session_key)) 127 os.unlink(self._key_to_io_lock_file(session_key)) 103 128 except OSError: 104 129 pass 105 130