Download the given URL and return the file name.
(self, url)
| 291 | ) |
| 292 | |
| 293 | def download(self, url): |
| 294 | """ |
| 295 | Download the given URL and return the file name. |
| 296 | """ |
| 297 | |
| 298 | def cleanup_url(url): |
| 299 | tmp = url.rstrip("/") |
| 300 | filename = tmp.split("/")[-1] |
| 301 | if url.endswith("/"): |
| 302 | display_url = tmp + "/" |
| 303 | else: |
| 304 | display_url = url |
| 305 | return filename, display_url |
| 306 | |
| 307 | prefix = "django_%s_template_" % self.app_or_project |
| 308 | tempdir = tempfile.mkdtemp(prefix=prefix, suffix="_download") |
| 309 | self.paths_to_remove.append(tempdir) |
| 310 | filename, display_url = cleanup_url(url) |
| 311 | |
| 312 | if self.verbosity >= 2: |
| 313 | self.stdout.write("Downloading %s" % display_url) |
| 314 | |
| 315 | the_path = os.path.join(tempdir, filename) |
| 316 | opener = build_opener() |
| 317 | opener.addheaders = [("User-Agent", f"Django/{django.__version__}")] |
| 318 | try: |
| 319 | with opener.open(url) as source, open(the_path, "wb") as target: |
| 320 | headers = source.info() |
| 321 | target.write(source.read()) |
| 322 | except OSError as e: |
| 323 | raise CommandError( |
| 324 | "couldn't download URL %s to %s: %s" % (url, filename, e) |
| 325 | ) |
| 326 | |
| 327 | used_name = the_path.split("/")[-1] |
| 328 | |
| 329 | # Trying to get better name from response headers |
| 330 | content_disposition = headers["content-disposition"] |
| 331 | if content_disposition: |
| 332 | _, params = parse_header_parameters(content_disposition) |
| 333 | guessed_filename = params.get("filename") or used_name |
| 334 | else: |
| 335 | guessed_filename = used_name |
| 336 | |
| 337 | # Falling back to content type guessing |
| 338 | ext = self.splitext(guessed_filename)[1] |
| 339 | content_type = headers["content-type"] |
| 340 | if not ext and content_type: |
| 341 | ext = mimetypes.guess_extension(content_type) |
| 342 | if ext: |
| 343 | guessed_filename += ext |
| 344 | |
| 345 | # Move the temporary file to a filename that has better |
| 346 | # chances of being recognized by the archive utils |
| 347 | if used_name != guessed_filename: |
| 348 | guessed_path = os.path.join(tempdir, guessed_filename) |
| 349 | shutil.move(the_path, guessed_path) |
| 350 | return guessed_path |
no test coverage detected