| 79 | | fd = os.open(self._key_to_file(self.session_key), flags) |
| 80 | | try: |
| 81 | | os.write(fd, self.encode(session_data)) |
| 82 | | finally: |
| 83 | | os.close(fd) |
| | 83 | # Make sure the file exists. If it does not already exist, an |
| | 84 | # empty placeholder file is created. |
| | 85 | flags = os.O_WRONLY | os.O_CREAT | getattr(os, 'O_BINARY', 0) |
| | 86 | if must_create: |
| | 87 | flags |= os.O_EXCL |
| | 88 | fd = os.open(session_file_name, flags) |
| | 89 | os.close(fd) |
| | 90 | |
| 88 | | except (IOError, EOFError): |
| | 95 | |
| | 96 | # Write the session file without interfering with other threads |
| | 97 | # or processes. By writing to an atomically generated temporary |
| | 98 | # file and then using the atomic os.rename() to make the complete |
| | 99 | # file visible, we avoid having to lock the session file, while |
| | 100 | # still maintaining its integrity. |
| | 101 | # |
| | 102 | # Note: Locking the session file was explored, but rejected in part |
| | 103 | # because in order to be atomic and cross-platform, it required a |
| | 104 | # long-lived lock file for each session, doubling the number of |
| | 105 | # files in the session storage directory at any given time. This |
| | 106 | # rename solution is cleaner and avoids any additional overhead |
| | 107 | # when reading the session data, which is the more common case |
| | 108 | # unless SESSION_SAVE_EVERY_REQUEST = True. |
| | 109 | # |
| | 110 | # See ticket #8616. |
| | 111 | dir, prefix = os.path.split(session_file_name) |
| | 112 | |
| | 113 | try: |
| | 114 | output_file_fd, output_file_name = tempfile.mkstemp(dir=dir, |
| | 115 | prefix=prefix + '_out_') |
| | 116 | try: |
| | 117 | try: |
| | 118 | os.write(output_file_fd, self.encode(session_data)) |
| | 119 | finally: |
| | 120 | os.close(output_file_fd) |
| | 121 | os.rename(output_file_name, session_file_name) |
| | 122 | finally: |
| | 123 | os.unlink(output_file_name) |
| | 124 | |
| | 125 | except (OSError, IOError, EOFError): |