Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

temp.py 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """
  2. The temp module provides a NamedTemporaryFile that can be reopened in the same
  3. process on any platform. Most platforms use the standard Python
  4. tempfile.NamedTemporaryFile class, but Windows users are given a custom class.
  5. This is needed because the Python implementation of NamedTemporaryFile uses the
  6. O_TEMPORARY flag under Windows, which prevents the file from being reopened
  7. if the same flag is not provided [1][2]. Note that this does not address the
  8. more general issue of opening a file for writing and reading in multiple
  9. processes in a manner that works across platforms.
  10. The custom version of NamedTemporaryFile doesn't support the same keyword
  11. arguments available in tempfile.NamedTemporaryFile.
  12. 1: https://mail.python.org/pipermail/python-list/2005-December/336957.html
  13. 2: http://bugs.python.org/issue14243
  14. """
  15. import os
  16. import tempfile
  17. from django.core.files.utils import FileProxyMixin
  18. __all__ = ('NamedTemporaryFile', 'gettempdir',)
  19. if os.name == 'nt':
  20. class TemporaryFile(FileProxyMixin):
  21. """
  22. Temporary file object constructor that supports reopening of the
  23. temporary file in Windows.
  24. Unlike tempfile.NamedTemporaryFile from the standard library,
  25. __init__() doesn't support the 'delete', 'buffering', 'encoding', or
  26. 'newline' keyword arguments.
  27. """
  28. def __init__(self, mode='w+b', bufsize=-1, suffix='', prefix='', dir=None):
  29. fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
  30. self.name = name
  31. self.file = os.fdopen(fd, mode, bufsize)
  32. self.close_called = False
  33. # Because close can be called during shutdown
  34. # we need to cache os.unlink and access it
  35. # as self.unlink only
  36. unlink = os.unlink
  37. def close(self):
  38. if not self.close_called:
  39. self.close_called = True
  40. try:
  41. self.file.close()
  42. except (OSError, IOError):
  43. pass
  44. try:
  45. self.unlink(self.name)
  46. except OSError:
  47. pass
  48. def __del__(self):
  49. self.close()
  50. def __enter__(self):
  51. self.file.__enter__()
  52. return self
  53. def __exit__(self, exc, value, tb):
  54. self.file.__exit__(exc, value, tb)
  55. NamedTemporaryFile = TemporaryFile
  56. else:
  57. NamedTemporaryFile = tempfile.NamedTemporaryFile
  58. gettempdir = tempfile.gettempdir