本文整理匯總了Python中mimetypes.guess_extension方法的典型用法代碼示例。如果您正苦於以下問題:Python mimetypes.guess_extension方法的具體用法?Python mimetypes.guess_extension怎麽用?Python mimetypes.guess_extension使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類mimetypes
的用法示例。
在下文中一共展示了mimetypes.guess_extension方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: upload_audio
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def upload_audio(self, file_id, mime):
if not self.file_store:
return None, "No file store available"
filedata = self.download_file(file_id)
if filedata is None:
return None, "teleboto Faild to download file"
if mime is None:
mime = magic.from_buffer(filedata, mime=True).decode('utf-8')
ext = mimetypes.guess_extension(mime)
if ext is None:
raise Exception("Failed to guess ext from mime: %s" % mime)
filename = "voice" + ext
url = self.file_store.upload_file(filedata, filename, filetype="audio")
if url is None:
return None, "Failed to upload Document"
return url, None
示例2: get_extension
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def get_extension(media):
"""Gets the corresponding extension for any Telegram media."""
# Photos are always compressed as .jpg by Telegram
try:
get_input_photo(media)
return '.jpg'
except TypeError:
# These cases are not handled by input photo because it can't
if isinstance(media, (types.UserProfilePhoto, types.ChatPhoto)):
return '.jpg'
# Documents will come with a mime type
if isinstance(media, types.MessageMediaDocument):
media = media.document
if isinstance(media, (
types.Document, types.WebDocument, types.WebDocumentNoProxy)):
if media.mime_type == 'application/octet-stream':
# Octet stream are just bytes, which have no default extension
return ''
else:
return guess_extension(media.mime_type) or ''
return ''
示例3: test_data_file_is_uploaded___file_can_be_retrieved
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def test_data_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
with TemporaryDirectory() as d:
with override_settings(MEDIA_ROOT=d):
user = fake_user()
cmf = fake_data_file()
self.app.post(
cmf.get_absolute_data_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
upload_files=(
('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
),
)
response = self.app.get(
cmf.get_absolute_data_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
)
self.assertEqual(response.body, file_content)
self.assertEqual(response.content_type, content_type)
示例4: test_accounts_file_is_uploaded___file_can_be_retrieved
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def test_accounts_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
with TemporaryDirectory() as d:
with override_settings(MEDIA_ROOT=d):
user = fake_user()
portfolio = fake_portfolio()
self.app.post(
portfolio.get_absolute_accounts_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
upload_files=(
('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
),
)
response = self.app.get(
portfolio.get_absolute_accounts_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
)
self.assertEqual(response.body, file_content)
self.assertEqual(response.content_type, content_type)
示例5: test_location_file_is_uploaded___file_can_be_retrieved
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def test_location_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
with TemporaryDirectory() as d:
with override_settings(MEDIA_ROOT=d):
user = fake_user()
portfolio = fake_portfolio()
self.app.post(
portfolio.get_absolute_location_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
upload_files=(
('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
),
)
response = self.app.get(
portfolio.get_absolute_location_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
)
self.assertEqual(response.body, file_content)
self.assertEqual(response.content_type, content_type)
示例6: test_reinsurance_scope_file_is_uploaded___file_can_be_retrieved
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def test_reinsurance_scope_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
with TemporaryDirectory() as d:
with override_settings(MEDIA_ROOT=d):
user = fake_user()
portfolio = fake_portfolio()
self.app.post(
portfolio.get_absolute_reinsurance_scope_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
upload_files=(
('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
),
)
response = self.app.get(
portfolio.get_absolute_reinsurance_scope_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
)
self.assertEqual(response.body, file_content)
self.assertEqual(response.content_type, content_type)
示例7: test_reinsurance_info_file_is_uploaded___file_can_be_retrieved
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def test_reinsurance_info_file_is_uploaded___file_can_be_retrieved(self, file_content, content_type):
with TemporaryDirectory() as d:
with override_settings(MEDIA_ROOT=d):
user = fake_user()
portfolio = fake_portfolio()
self.app.post(
portfolio.get_absolute_reinsurance_info_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
upload_files=(
('file', 'file{}'.format(mimetypes.guess_extension(content_type)), file_content),
),
)
response = self.app.get(
portfolio.get_absolute_reinsurance_info_file_url(),
headers={
'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
},
)
self.assertEqual(response.body, file_content)
self.assertEqual(response.content_type, content_type)
示例8: filter_filename
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def filter_filename(cls, filename, storage_name, content_type, content_type_hint):
"""
Filter filename.
Only allow some basic characters and shorten to 50 characters.
"""
# Make up filename if we don't have one
if not filename:
if not content_type:
content_type = content_type_hint
# note: stdlib mimetypes.guess_extension is total crap
if content_type.startswith("text/"):
ext = ".txt"
else:
ext = ".bin"
filename = storage_name + ext
return cls._filename_re.sub('', filename)[:MAX_FILENAME_LENGTH]
示例9: _get_http_response_filename
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
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
示例10: _savePartToFile
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def _savePartToFile(self, messagePart):
fn = messagePart.get_filename()
counter = 0
if not fn:
ext = mimetypes.guess_extension(messagePart.get_content_type()) # Bug in python returns .ksh for text/plain. Wait for python fix?
if not ext:
# generic extension?
ext = '.bin'
fn = 'emailpart%s' % (ext)
fn = os.path.basename(fn) # Sanitize Filename.
attempted_filename = fn
while os.path.exists(os.path.join(self.DOWNLOAD_DIR, attempted_filename)):
counter += 1
attempted_filename = "%s%s%s" % (os.path.splitext(fn)[0], counter, os.path.splitext(fn)[1])
fn = attempted_filename
fqfn = os.path.join(self.DOWNLOAD_DIR, fn)
if messagePart.get_content_maintype() == "text":
with open(fqfn, 'w') as f:
f.write(messagePart.get_payload(decode=True))
else:
with open(fqfn, 'wb') as f:
f.write(messagePart.get_payload(decode=True))
示例11: get_file_info
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def get_file_info(request: HttpRequest, user_file: File) -> Tuple[str, int, Optional[str]]:
uploaded_file_name = user_file.name
content_type = request.GET.get('mimetype')
if content_type is None:
guessed_type = guess_type(uploaded_file_name)[0]
if guessed_type is not None:
content_type = guessed_type
else:
extension = guess_extension(content_type)
if extension is not None:
uploaded_file_name = uploaded_file_name + extension
uploaded_file_name = urllib.parse.unquote(uploaded_file_name)
uploaded_file_size = user_file.size
return uploaded_file_name, uploaded_file_size, content_type
示例12: name
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def name(self):
"""
Returns the filename
"""
if self._name:
# return our fixed content
return self._name
if not self.exists():
# we could not obtain our name
return None
if not self.detected_name:
# If we get here, our download was successful but we don't have a
# filename based on our content.
extension = mimetypes.guess_extension(self.mimetype)
self.detected_name = '{}{}'.format(
self.unknown_filename,
extension if extension else self.unknown_filename_extension)
return self.detected_name
示例13: guess_extension
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def guess_extension(mime):
"""
This function gets extensions from mimes, and if it can't find it uses the standard guesses
:param mime: a mimetype string
:return: a string containing a file extension eg. doc or docx
"""
if mime == 'text/plain':
extension = 'txt'
elif mime == 'application/msword':
extension = 'doc'
elif mime == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
extension = 'docx'
elif mime == 'application/vnd.oasis.opendocument.text':
extension = 'odt'
elif mime == 'text/html;charset=UTF-8':
extension = 'html'
else:
extension = mimetypes.guess_extension(mime)
return extension
示例14: get_filename
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def get_filename(self, content_type):
if not self._basename:
return None
typeValue = map(str.strip, content_type.split(";"))
if len(typeValue) == 0:
return None
extension = mimetypes.guess_extension(typeValue[0])
if not extension:
return None
return "%s%s" % (self._basename, extension)
#~~ admin access validator for use with tornado
示例15: __init__
# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_extension [as 別名]
def __init__(self, source, *args, **kwargs):
super().__init__(source, *args, **kwargs)
self.path = os.path.abspath(os.path.expanduser(
self.source[len(self._matched_handler):]))
self.filename = self.path.split('/')[-1]
if not os.path.isfile(self.path):
raise FileNotFoundError('{} is not a valid file'.
format(self.path))
self.mime_type = get_mime_type(source)
if self.mime_type[:5] not in ['video', 'audio', 'image']:
raise AttributeError('{} is not a valid media file (detected format: {})'.
format(source, self.mime_type))
self.extension = mimetypes.guess_extension(self.mime_type)
if self.url:
self.url += self.extension
self.content_length = os.path.getsize(self.path)