Add Django-1.2.1
[frozenviper.git] / Django-1.2.1 / django / core / files / temp.py
blobb6072912945bd4c3cf107fc0323747b90a9ff50c
1 """
2 The temp module provides a NamedTemporaryFile that can be re-opened on any
3 platform. Most platforms use the standard Python tempfile.TemporaryFile class,
4 but MS Windows users are given a custom class.
6 This is needed because in Windows NT, the default implementation of
7 NamedTemporaryFile uses the O_TEMPORARY flag, and thus cannot be reopened [1].
9 1: http://mail.python.org/pipermail/python-list/2005-December/359474.html
10 """
12 import os
13 import tempfile
14 from django.core.files.utils import FileProxyMixin
16 __all__ = ('NamedTemporaryFile', 'gettempdir',)
18 if os.name == 'nt':
19 class TemporaryFile(FileProxyMixin):
20 """
21 Temporary file object constructor that works in Windows and supports
22 reopening of the temporary file in windows.
23 """
24 def __init__(self, mode='w+b', bufsize=-1, suffix='', prefix='',
25 dir=None):
26 fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix,
27 dir=dir)
28 self.name = name
29 self.file = os.fdopen(fd, mode, bufsize)
30 self.close_called = False
32 # Because close can be called during shutdown
33 # we need to cache os.unlink and access it
34 # as self.unlink only
35 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
49 def __del__(self):
50 self.close()
52 NamedTemporaryFile = TemporaryFile
53 else:
54 NamedTemporaryFile = tempfile.NamedTemporaryFile
56 gettempdir = tempfile.gettempdir