本文整理汇总了Python中mimetypes.guess_type方法的典型用法代码示例。如果您正苦于以下问题:Python mimetypes.guess_type方法的具体用法?Python mimetypes.guess_type怎么用?Python mimetypes.guess_type使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mimetypes
的用法示例。
在下文中一共展示了mimetypes.guess_type方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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])
示例2: encode_multipart_formdata
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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
示例3: upload_files
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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)
示例4: send_file
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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)
示例5: sendFile
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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))
示例6: open_local_file
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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')
示例7: upload_a_picture
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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()
示例8: get_content_type
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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"
示例9: testdata_scheme
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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
示例10: upload_doc
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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()
示例11: asgi_send_file
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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}
)
示例12: async_callback_download
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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))
示例13: synchronous
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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))
示例14: add_file
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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)
示例15: get_type_headers
# 需要导入模块: import mimetypes [as 别名]
# 或者: from mimetypes import guess_type [as 别名]
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