Construct download name in separate function
Later, we will use this to make a dedicated object that represents
our download.
@@ -400,6 +400,30 @@ def parse_content_disposition(content_disposition, default_filename):
return filename or default_filename
+def _get_http_response_filename(resp, link):
+ # type: (Response, Link) -> str
+ """Get an ideal filename from the given HTTP response, falling back to
+ the link filename if not provided.
+ """
+ filename = link.filename # fallback
+ # Have a look at the Content-Disposition header for a better guess
+ content_disposition = resp.headers.get('content-disposition')
+ if content_disposition:
+ filename = parse_content_disposition(content_disposition, filename)
+ ext = splitext(filename)[1] # type: Optional[str]
+ if not ext:
+ ext = mimetypes.guess_extension(
+ resp.headers.get('content-type', '')
+ )
+ if ext:
+ filename += ext
+ if not ext and link.url != resp.url:
+ ext = os.path.splitext(resp.url)[1]
+ if ext:
+ filename += ext
+ return filename
+
+
def _download_http_url(
link, # type: Link
session, # type: PipSession
@@ -442,22 +466,7 @@ def _download_http_url(
)
raise
- filename = link.filename # fallback
- # Have a look at the Content-Disposition header for a better guess
- content_disposition = resp.headers.get('content-disposition')
- if content_disposition:
- filename = parse_content_disposition(content_disposition, filename)
- ext = splitext(filename)[1] # type: Optional[str]
- if not ext:
- ext = mimetypes.guess_extension(
- resp.headers.get('content-type', '')
- )
- if ext:
- filename += ext
- if not ext and link.url != resp.url:
- ext = os.path.splitext(resp.url)[1]
- if ext:
- filename += ext
+ filename = _get_http_response_filename(resp, link)
file_path = os.path.join(temp_dir, filename)
with open(file_path, 'wb') as content_file:
_download_url(resp, link, content_file, hashes, progress_bar)
