55import mimetypes
66import os
77import posixpath
8- import shutil
98import tempfile
109
1110
1211class DownloadedFile (tempfile ._TemporaryFileWrapper ):
12+ basename = None
13+
1314 def __repr__ (self ):
1415 state = "closed" if self .close_called else "open"
1516 mode = "" if self .close_called else " '%s'" % self .file .mode
@@ -98,6 +99,8 @@ def _get_filename(base_url=None, content_type=None, content_disposition=None):
9899 filename = _get_filename_from_content_disposition (content_disposition )
99100 if base_url and not filename :
100101 filename = _get_filename_from_url (base_url , content_type )
102+ if not filename :
103+ return None # Ensure empty filenames return as `None` for consistency.
101104 return filename
102105
103106
@@ -111,17 +114,11 @@ def __init__(self, download_dir=None):
111114 """
112115 `download_dir` - The path to use for file downloads.
113116 """
114- self ._temporary = download_dir is None
117+ self ._delete_on_close = download_dir is None
115118 self ._download_dir = download_dir
116119
117- def __del__ (self ):
118- if self ._temporary and self ._download_dir :
119- shutil .rmtree (self ._download_dir )
120-
121120 @property
122121 def download_dir (self ):
123- if self ._download_dir is None :
124- self ._download_dir = tempfile .mkdtemp (prefix = 'temp-coreapi-download-' )
125122 return self ._download_dir
126123
127124 def decode (self , bytestring , ** options ):
@@ -137,15 +134,21 @@ def decode(self, bytestring, **options):
137134
138135 # Determine the output filename.
139136 output_filename = _get_filename (base_url , content_type , content_disposition )
140- if not output_filename :
141- # Fallback if no output filename could be determined.
137+ if output_filename is None :
142138 output_filename = os .path .basename (temp_path )
143139
140+ # Determine the output directory.
141+ output_dir = self ._download_dir
142+ if output_dir is None :
143+ output_dir = os .path .dirname (temp_path )
144+
144145 # Determine the full output path.
145- output_path = os .path .join (self . download_dir , output_filename )
146+ output_path = os .path .join (output_dir , output_filename )
146147 output_path = _unique_output_path (output_path )
147148
148149 # Move the temporary download file to the final location.
149150 os .rename (temp_path , output_path )
150151 output_file = open (output_path , 'rb' )
151- return DownloadedFile (output_file , output_path , delete = self ._temporary )
152+ downloaded = DownloadedFile (output_file , output_path , delete = self ._delete_on_close )
153+ downloaded .basename = output_filename
154+ return downloaded
0 commit comments