comparison core/download.py @ 973:6f55c086db1e

Guess file extension based on content-type. When downloading a file, and no path is supplied to store it, guess the file extension using mimetypes and the content-type header. Also supply a unit test for the HotLinkImageForm.
author Brian Neal <bgneal@gmail.com>
date Thu, 01 Oct 2015 19:44:45 -0500
parents 7138883966b3
children f5aa74dcdd7a
comparison
equal deleted inserted replaced
972:7138883966b3 973:6f55c086db1e
1 """This module contains routines for downloading files.""" 1 """This module contains routines for downloading files."""
2 2
3 import logging 3 import logging
4 import mimetypes
4 import os 5 import os
5 import shutil 6 import shutil
6 import tempfile 7 import tempfile
7 8
8 import requests 9 import requests
33 return None 34 return None
34 35
35 # Save file data 36 # Save file data
36 37
37 if not path: 38 if not path:
38 fd, path = tempfile.mkstemp() 39 content_type = r.headers.get('content-type')
40 suffix = mimetypes.guess_extension(content_type) if content_type else ''
41 if suffix == '.jpe':
42 suffix = '.jpg'
43 fd, path = tempfile.mkstemp(suffix=suffix)
39 os.close(fd) 44 os.close(fd)
40 45
41 try: 46 try:
42 with open(path, 'wb') as fp: 47 with open(path, 'wb') as fp:
43 r.raw.decode_content = True 48 r.raw.decode_content = True