当前位置: 首页>>代码示例>>Python>>正文


Python mimetypes.guess_extension方法代码示例

本文整理汇总了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 
开发者ID:tuna,项目名称:fishroom,代码行数:21,代码来源:telegram.py

示例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 '' 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:26,代码来源:utils.py

示例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) 
开发者ID:OasisLMF,项目名称:OasisPlatform,代码行数:27,代码来源:test_data_files.py

示例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) 
开发者ID:OasisLMF,项目名称:OasisPlatform,代码行数:27,代码来源:test_portfolio.py

示例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) 
开发者ID:OasisLMF,项目名称:OasisPlatform,代码行数:27,代码来源:test_portfolio.py

示例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) 
开发者ID:OasisLMF,项目名称:OasisPlatform,代码行数:27,代码来源:test_portfolio.py

示例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) 
开发者ID:OasisLMF,项目名称:OasisPlatform,代码行数:27,代码来源:test_portfolio.py

示例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] 
开发者ID:bepasty,项目名称:bepasty-server,代码行数:18,代码来源:upload.py

示例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 
开发者ID:pantsbuild,项目名称:pex,代码行数:24,代码来源:download.py

示例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)) 
开发者ID:hexway,项目名称:apple_bleee,代码行数:24,代码来源:stdfmemail.py

示例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 
开发者ID:zulip,项目名称:zulip,代码行数:19,代码来源:upload.py

示例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 
开发者ID:caronc,项目名称:apprise,代码行数:23,代码来源:AttachBase.py

示例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 
开发者ID:BirkbeckCTP,项目名称:janeway,代码行数:22,代码来源:shared.py

示例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 
开发者ID:AstroPrint,项目名称:AstroBox,代码行数:18,代码来源:util.py

示例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) 
开发者ID:BlackLight,项目名称:platypush,代码行数:22,代码来源:file.py


注:本文中的mimetypes.guess_extension方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。