Race condition in setitem() of session.DiskStore

DiskStore.setitem() does f.open(), f.write(), f.close() of session data. Problem is, if different thread attempt to open and read the same file, while the file is already opened for f.write(). The read returns zero bytes, resulting in session data decode failure, which percolates back as a session failure.

Solution can be to instead open a temporary file, write & close the temporary file, and then rename it to the proper file. This is guaranteed atomic. That way, there's always a valid session DiskStore.

session.py, approx line 260:

class DiskStore(Store):
....
  def __setitem__(self, key, value):
    path = ...
    pickled = ...
    try:
        f = tempfile.NamedTemporaryFile(delete=False)  # use tempfile rather that path
        try:
            f.write(pickled)
        finally:
            f.close()
            os.rename(f.name, path)  # update path atomically
    except IOError:
        pass