Debian Codegraph @

django/core/files/temp.py

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