Python mimetypes.guess_type() Examples
The following are 30
code examples of mimetypes.guess_type().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
mimetypes
, or try the search function
.
Example #1
Source File: http_lib.py From marketo-rest-python with MIT License | 8 votes |
def post(self, endpoint, args, data=None, files=None, filename=None, mode=None): if mode == 'nojsondumps': headers = {'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'} r = requests.post(endpoint, params=args, data=data, headers=headers) elif files is None: headers = {'Content-type': 'application/json; charset=utf-8'} r = requests.post(endpoint, params=args, json=data, headers=headers) elif files is not None: mimetype = mimetypes.guess_type(files)[0] file = {filename: (files, open(files, 'rb'), mimetype)} r = requests.post(endpoint, params=args, json=data, files=file) r_json = r.json() if r_json.get('success'): return r_json else: raise MarketoException(r_json['errors'][0])
Example #2
Source File: utils.py From Jike-Metro with MIT License | 7 votes |
def upload_a_picture(picture): assert os.path.exists(picture) name = os.path.split(picture)[1] mimetype, _ = guess_type(name) assert mimetype if not mimetype.startswith('image'): raise ValueError('Cannot upload file: {}, which is not picture'.format(name)) uptoken = get_uptoken() with open(picture, 'rb') as fp: files = {'token': (None, uptoken), 'file': (name, fp, mimetype)} res = requests.post(ENDPOINTS['picture_upload'], files=files) if res.status_code == 200: result = res.json() if result['success']: return result['key'] else: raise RuntimeError('Picture upload fail') res.raise_for_status()
Example #3
Source File: ptpimg_uploader.py From ptpimg-uploader with BSD 2-Clause "Simplified" License | 7 votes |
def upload_files(self, *filenames): """ Upload files using form """ # The ExitStack closes files for us when the with block exits with contextlib.ExitStack() as stack: files = {} for i, filename in enumerate(filenames): open_file = stack.enter_context(open(filename, 'rb')) mime_type, _ = mimetypes.guess_type(filename) if not mime_type or mime_type.split('/')[0] != 'image': raise ValueError( 'Unknown image file type {}'.format(mime_type)) name = os.path.basename(filename) try: # until https://github.com/shazow/urllib3/issues/303 is # resolved, only use the filename if it is Latin-1 safe name.encode('latin1') except UnicodeEncodeError: name = 'justfilename' files['file-upload[{}]'.format(i)] = ( name, open_file, mime_type) return self._perform(files=files)
Example #4
Source File: fixtures.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def testdata_scheme(qapp): try: global _qute_scheme_handler from qutebrowser.browser.webengine import webenginequtescheme from PyQt5.QtWebEngineWidgets import QWebEngineProfile webenginequtescheme.init() _qute_scheme_handler = webenginequtescheme.QuteSchemeHandler( parent=qapp) _qute_scheme_handler.install(QWebEngineProfile.defaultProfile()) except ImportError: pass @qutescheme.add_handler('testdata') def handler(url): # pylint: disable=unused-variable file_abs = os.path.abspath(os.path.dirname(__file__)) filename = os.path.join(file_abs, os.pardir, 'end2end', url.path().lstrip('/')) with open(filename, 'rb') as f: data = f.read() mimetype, _encoding = mimetypes.guess_type(filename) return mimetype, data
Example #5
Source File: asgi.py From datasette with Apache License 2.0 | 6 votes |
def asgi_send_file( send, filepath, filename=None, content_type=None, chunk_size=4096 ): headers = {} if filename: headers["Content-Disposition"] = 'attachment; filename="{}"'.format(filename) first = True async with aiofiles.open(str(filepath), mode="rb") as fp: if first: await asgi_start( send, 200, headers, content_type or guess_type(str(filepath))[0] or "text/plain", ) first = False more_body = True while more_body: chunk = await fp.read(chunk_size) more_body = len(chunk) == chunk_size await send( {"type": "http.response.body", "body": chunk, "more_body": more_body} )
Example #6
Source File: media.py From pybotgram with GNU Affero General Public License v3.0 | 6 votes |
def async_callback_download(path, ext, receiver): if path is None: return mimetype, _ = mimetypes.guess_type(path) if not mimetype: return mime = mimetype.split('/')[0] f = tgl.send_file if ext == "gif" or ext == "webp" or mime == "text": f = tgl.send_document elif mime == "image": f = tgl.send_image elif mime == "audio": f = tgl.send_audio elif mime == "video": f = tgl.send_video print("Sending file with mime {} from path {}".format(mimetype, path)) f(receiver, path, utils.cb_rmp(path))
Example #7
Source File: media.py From pybotgram with GNU Affero General Public License v3.0 | 6 votes |
def synchronous(url, ext, receiver): path = '' try: path = utils.download_to_file(url, ext) except: print("Error downloading {}".format(url)) return mimetype, _ = mimetypes.guess_type(path) if not mimetype: return mime = mimetype.split('/')[0] f = tgl.send_file if ext == "gif" or ext == "webp" or mime == "text": f = tgl.send_document elif mime == "image": f = tgl.send_image elif mime == "audio": f = tgl.send_audio elif mime == "video": f = tgl.send_video print("Sending file with mime {} from path {}".format(mimetype, path)) f(receiver, path, utils.cb_rmp(path))
Example #8
Source File: onenote.py From WizNote-to-OneNote with Apache License 2.0 | 6 votes |
def upload_doc(session, section_id, data_path, doc): doc_path = get_doc_path(data_path, doc) print('Processing %s%s (%s)' % (doc.location, doc.title, doc.guid)) with ZipFile(doc_path) as zip_file: html_content, src_file_names = clean_html(zip_file.read('index.html'), doc) if len(src_file_names) > 5: print('Upload may failed if images more than 5') data_send = { 'Presentation': (None, html_content, mimetypes.guess_type('index.html')[0]) } for name in src_file_names: data_send[name] = (None, zip_file.read('index_files/' + name), mimetypes.guess_type(name)[0]) resp = session.post(API_BASE + '/sections/%s/pages' % section_id, files=data_send) resp.raise_for_status()
Example #9
Source File: urllib2.py From jawfish with MIT License | 6 votes |
def open_local_file(self, req): host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats[stat.ST_SIZE] modified = rfc822.formatdate(stats[stat.ST_MTIME]) mtype = mimetypes.guess_type(file)[0] stats = os.stat(localfile) headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if host: host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) raise URLError('file not on local host')
Example #10
Source File: twisted-server.py From hyper-h2 with MIT License | 6 votes |
def sendFile(self, file_path, stream_id): filesize = os.stat(file_path).st_size content_type, content_encoding = mimetypes.guess_type( file_path.decode('utf-8') ) response_headers = [ (':status', '200'), ('content-length', str(filesize)), ('server', 'twisted-h2'), ] if content_type: response_headers.append(('content-type', content_type)) if content_encoding: response_headers.append(('content-encoding', content_encoding)) self.conn.send_headers(stream_id, response_headers) self.transport.write(self.conn.data_to_send()) f = open(file_path, 'rb') d = self._send_file(f, stream_id) d.addErrback(functools.partial(close_file, f))
Example #11
Source File: curio-server.py From hyper-h2 with MIT License | 6 votes |
def send_file(self, file_path, stream_id): """ Send a file, obeying the rules of HTTP/2 flow control. """ filesize = os.stat(file_path).st_size content_type, content_encoding = mimetypes.guess_type(file_path) response_headers = [ (':status', '200'), ('content-length', str(filesize)), ('server', 'curio-h2'), ] if content_type: response_headers.append(('content-type', content_type)) if content_encoding: response_headers.append(('content-encoding', content_encoding)) self.conn.send_headers(stream_id, response_headers) await self.sock.sendall(self.conn.data_to_send()) with open(file_path, 'rb', buffering=0) as f: await self._send_file_data(f, stream_id)
Example #12
Source File: mimetype.py From pagure with GNU General Public License v2.0 | 6 votes |
def get_type_headers(filename, data): """ Get the HTTP headers used for downloading or previewing the file. If the file is html, it will return headers which make browser start downloading. :param filename: file name string :param data: file data string """ mimetype, encoding = guess_type(filename, data) if not mimetype: return None headers = {str("X-Content-Type-Options"): "nosniff"} if "html" in mimetype or "javascript" in mimetype or "svg" in mimetype: mimetype = "application/octet-stream" headers[str("Content-Disposition")] = "attachment" if encoding: mimetype += "; charset={encoding}".format(encoding=encoding) headers[str("Content-Type")] = mimetype return headers
Example #13
Source File: web.py From tornado-zh with MIT License | 6 votes |
def get_content_type(self): """返回这个请求使用的 ``Content-Type`` 头. .. versionadded:: 3.1 """ mime_type, encoding = mimetypes.guess_type(self.absolute_path) # per RFC 6713, use the appropriate type for a gzip compressed file if encoding == "gzip": return "application/gzip" # As of 2015-07-21 there is no bzip2 encoding defined at # http://www.iana.org/assignments/media-types/media-types.xhtml # So for that (and any other encoding), use octet-stream. elif encoding is not None: return "application/octet-stream" elif mime_type is not None: return mime_type # if mime_type not detected, use application/octet-stream else: return "application/octet-stream"
Example #14
Source File: datastructures.py From recruit with Apache License 2.0 | 6 votes |
def add_file(self, name, file, filename=None, content_type=None): """Adds a new file to the dict. `file` can be a file name or a :class:`file`-like or a :class:`FileStorage` object. :param name: the name of the field. :param file: a filename or :class:`file`-like object :param filename: an optional filename :param content_type: an optional content type """ if isinstance(file, FileStorage): value = file else: if isinstance(file, string_types): if filename is None: filename = file file = open(file, "rb") if filename and content_type is None: content_type = ( mimetypes.guess_type(filename)[0] or "application/octet-stream" ) value = FileStorage(file, filename, name, content_type) self.add(name, value)
Example #15
Source File: web.py From tornado-zh with MIT License | 6 votes |
def get_content_type(self): """返回这个请求使用的 ``Content-Type`` 头. .. versionadded:: 3.1 """ mime_type, encoding = mimetypes.guess_type(self.absolute_path) # per RFC 6713, use the appropriate type for a gzip compressed file if encoding == "gzip": return "application/gzip" # As of 2015-07-21 there is no bzip2 encoding defined at # http://www.iana.org/assignments/media-types/media-types.xhtml # So for that (and any other encoding), use octet-stream. elif encoding is not None: return "application/octet-stream" elif mime_type is not None: return mime_type # if mime_type not detected, use application/octet-stream else: return "application/octet-stream"
Example #16
Source File: test_http.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def encode_multipart_formdata(files): """Return (content_type, body) ready for httplib.HTTP instance. files: a sequence of (name, filename, value) tuples for multipart uploads. filename can be a string or a tuple ('filename string', 'encoding') """ BOUNDARY = '________ThIs_Is_tHe_bouNdaRY_$' L = [] for key, filename, value in files: L.append('--' + BOUNDARY) fn_key, encoded = encode_filename(filename) tmpl = \ 'Content-Disposition: form-data; name="{key}"; {fn_key}={encoded}' L.append(tmpl.format(**locals())) ct = mimetypes.guess_type(filename)[0] or 'application/octet-stream' L.append('Content-Type: %s' % ct) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = '\r\n'.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body
Example #17
Source File: utils.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def guess_mimetype(filename: str, fallback: bool = False) -> str: """Guess a mimetype based on a filename. Args: filename: The filename to check. fallback: Fall back to application/octet-stream if unknown. """ mimetype, _encoding = mimetypes.guess_type(filename) if mimetype is None: if fallback: return 'application/octet-stream' else: raise ValueError("Got None mimetype for {}".format(filename)) return mimetype
Example #18
Source File: fields.py From ServerlessCrawler-VancouverRealState with MIT License | 5 votes |
def guess_content_type(filename, default='application/octet-stream'): """ Guess the "Content-Type" of a file. :param filename: The filename to guess the "Content-Type" of using :mod:`mimetypes`. :param default: If no "Content-Type" can be guessed, default to `default`. """ if filename: return mimetypes.guess_type(filename)[0] or default return default
Example #19
Source File: Smail.py From Smail with GNU General Public License v3.0 | 5 votes |
def add_attachment(self,filepath,filename=None): if filename == None: filename=os.path.basename(filepath) with open(filepath,'rb') as f: file=f.read() ctype, encoding = mimetypes.guess_type(filepath) if ctype is None or encoding is not None:ctype = "application/octet-stream" maintype, subtype = ctype.split('/', 1) if maintype == "text": with open(filepath) as f:file=f.read() attachment = MIMEText(file, _subtype=subtype) elif maintype == "image": with open(filepath,'rb') as f:file=f.read() attachment = MIMEImage(file, _subtype=subtype) elif maintype == "audio": with open(filepath,'rb') as f:file=f.read() attachment = MIMEAudio(file, _subtype=subtype) else: with open(filepath,'rb') as f:file=f.read() attachment = MIMEBase(maintype,subtype) attachment.set_payload(file) attachment.add_header('Content-Disposition', 'attachment', filename=filename) encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=filename) attachment.add_header('Content-ID',str(self.attachment_num)) self.attachment_num+=1 self.attachment_list.append(attachment)
Example #20
Source File: fields.py From recruit with Apache License 2.0 | 5 votes |
def guess_content_type(filename, default='application/octet-stream'): """ Guess the "Content-Type" of a file. :param filename: The filename to guess the "Content-Type" of using :mod:`mimetypes`. :param default: If no "Content-Type" can be guessed, default to `default`. """ if filename: return mimetypes.guess_type(filename)[0] or default return default
Example #21
Source File: mimetype.py From pagure with GNU General Public License v2.0 | 5 votes |
def guess_type(filename, data): """ Guess the type of a file based on its filename and data. Return value is a tuple (type, encoding) where type or encoding is None if it can't be guessed. :param filename: file name string :param data: file data string """ mimetype = None encoding = None if filename: mimetype, encoding = mimetypes.guess_type(filename) if data: if not mimetype: if not isinstance(data, six.text_type) and b"\0" in data: mimetype = "application/octet-stream" else: mimetype = "text/plain" if mimetype.startswith("text/") and not encoding: try: encoding = pagure.lib.encoding_utils.guess_encoding( ktc.to_bytes(data) ) except pagure.exceptions.PagureException: # pragma: no cover # We cannot decode the file, so bail but warn the admins _log.exception("File could not be decoded") return mimetype, encoding
Example #22
Source File: download.py From recruit with Apache License 2.0 | 5 votes |
def send(self, request, stream=None, timeout=None, verify=None, cert=None, proxies=None): pathname = url_to_path(request.url) resp = Response() resp.status_code = 200 resp.url = request.url try: stats = os.stat(pathname) except OSError as exc: resp.status_code = 404 resp.raw = exc else: modified = email.utils.formatdate(stats.st_mtime, usegmt=True) content_type = mimetypes.guess_type(pathname)[0] or "text/plain" resp.headers = CaseInsensitiveDict({ "Content-Type": content_type, "Content-Length": stats.st_size, "Last-Modified": modified, }) resp.raw = open(pathname, "rb") resp.close = resp.raw.close return resp
Example #23
Source File: __init__.py From recruit with Apache License 2.0 | 5 votes |
def get_resource(self, request, filename): """Return a static resource from the shared folder.""" filename = join("shared", basename(filename)) try: data = pkgutil.get_data(__package__, filename) except OSError: data = None if data is not None: mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" return Response(data, mimetype=mimetype) return Response("Not Found", status=404)
Example #24
Source File: fields.py From core with MIT License | 5 votes |
def guess_content_type(filename, default='application/octet-stream'): """ Guess the "Content-Type" of a file. :param filename: The filename to guess the "Content-Type" of using :mod:`mimetypes`. :param default: If no "Content-Type" can be guessed, default to `default`. """ if filename: return mimetypes.guess_type(filename)[0] or default return default
Example #25
Source File: mpupload.py From honeybee with GNU General Public License v3.0 | 5 votes |
def add_file(self, fieldname, filename, file_handle, mimetype=None): """Add a file to be uploaded.""" body = file_handle.read() if mimetype is None: mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' self.files.append((fieldname, filename, mimetype, body))
Example #26
Source File: request.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def open_local_file(self, req): import future.backports.email.utils as email_utils import mimetypes host = req.host filename = req.selector localfile = url2pathname(filename) try: stats = os.stat(localfile) size = stats.st_size modified = email_utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(filename)[0] headers = email.message_from_string( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified)) if host: host, port = splitport(host) if not host or \ (not port and _safe_gethostbyname(host) in self.get_names()): if host: origurl = 'file://' + host + filename else: origurl = 'file://' + filename return addinfourl(open(localfile, 'rb'), headers, origurl) except OSError as exp: # users shouldn't expect OSErrors coming from urlopen() raise URLError(exp) raise URLError('file not on local host')
Example #27
Source File: static_file_handler.py From browserscope with Apache License 2.0 | 5 votes |
def get(self, asset_name): """Serve out the contents of a file to self.response. Args: asset_name: The name of the static asset to serve. Must be in ASSETS_PATH. """ with self._asset_name_to_path_lock: if self._asset_name_to_path is None: self._initialize_asset_map() if asset_name in self._asset_name_to_path: asset_path = self._asset_name_to_path[asset_name] try: with open(asset_path, 'rb') as f: data = f.read() except (OSError, IOError): logging.exception('Error reading file %s', asset_path) self.response.set_status(500) else: content_type, _ = mimetypes.guess_type(asset_path) assert content_type, ( 'cannot determine content-type for %r' % asset_path ) self.response.headers['Content-Type'] = content_type self.response.out.write(data) else: self.response.set_status(404)
Example #28
Source File: request.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def open_local_file(self, url): """Use local file.""" import future.backports.email.utils as email_utils import mimetypes host, file = splithost(url) localname = url2pathname(file) try: stats = os.stat(localname) except OSError as e: raise URLError(e.strerror, e.filename) size = stats.st_size modified = email_utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(url)[0] headers = email.message_from_string( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified)) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) host, port = splitport(host) if (not port and socket.gethostbyname(host) in ((localhost(),) + thishost())): urlfile = file if file[:1] == '/': urlfile = 'file://' + file elif file[:2] == './': raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url) return addinfourl(open(localname, 'rb'), headers, urlfile) raise URLError('local file error: not on local host')
Example #29
Source File: appcfg.py From browserscope with Apache License 2.0 | 5 votes |
def __MimeType(filename, default='application/octet-stream'): guess = mimetypes.guess_type(filename)[0] if guess is None: print >>sys.stderr, ('Could not guess mimetype for %s. Using %s.' % (filename, default)) return default return guess
Example #30
Source File: request.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def open_local_file(self, req): import future.backports.email.utils as email_utils import mimetypes host = req.host filename = req.selector localfile = url2pathname(filename) try: stats = os.stat(localfile) size = stats.st_size modified = email_utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(filename)[0] headers = email.message_from_string( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified)) if host: host, port = splitport(host) if not host or \ (not port and _safe_gethostbyname(host) in self.get_names()): if host: origurl = 'file://' + host + filename else: origurl = 'file://' + filename return addinfourl(open(localfile, 'rb'), headers, origurl) except OSError as exp: # users shouldn't expect OSErrors coming from urlopen() raise URLError(exp) raise URLError('file not on local host')