python类MimeTypes()的实例源码

mail.py 文件源码 项目:do-portal 作者: certeu 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def send_email(subject, recipients, template, **kwargs):
    if not isinstance(recipients, list):
        recipients = list(recipients)
    msg = Message(subject, reply_to=current_app.config['MAIL_DEFAULT_SENDER'],
                  recipients=recipients)
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)

    attachments = kwargs.get('attachments', [])
    mimes = MimeTypes()
    for file in attachments:
        path_ = os.path.join(current_app.config['APP_UPLOADS'], file)
        with current_app.open_resource(path_) as fp:
            mime = mimes.guess_type(fp.name)
            msg.attach(path_, mime[0], fp.read())

    app = current_app._get_current_object()
    t = Thread(target=send_async_email, args=[app, msg])
    t.start()
    return t
models.py 文件源码 项目:wagtailvideos 作者: takeflight 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def video_tag(self, attrs=None):
        if attrs is None:
            attrs = {}
        else:
            attrs = attrs.copy()
        if self.thumbnail:
            attrs['poster'] = self.thumbnail.url

        transcodes = self.transcodes.exclude(processing=True).filter(error_message__exact='')
        sources = []
        for transcode in transcodes:
            sources.append("<source src='{0}' type='video/{1}' >".format(transcode.url, transcode.media_format.name))

        mime = mimetypes.MimeTypes()
        sources.append("<source src='{0}' type='{1}'>"
                       .format(self.url, mime.guess_type(self.url)[0]))

        sources.append("<p>Sorry, your browser doesn't support playback for this video</p>")
        return mark_safe(
            "<video {0}>\n{1}\n</video>".format(flatatt(attrs), "\n".join(sources)))
fab_ui_upload_logo.py 文件源码 项目:directory-tests 作者: uktrade 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def upload(session: Session, token: str, file_path: str) -> Response:
    """Upload logo.

    :param session: Supplier session object
    :param token: CSRF token required to upload the file
    :param file_path: absolute path to the uploaded file
    :return: response object
    """
    headers = {"Referer": get_absolute_url("ui-buyer:upload-logo")}
    url = get_absolute_url("ui-buyer:upload-logo")
    data = {
        "csrfmiddlewaretoken": token,
        "company_profile_logo_edit_view-current_step": "logo",
    }
    with open(file_path, "rb") as f:
        picture = f.read()
    mime = mimetypes.MimeTypes().guess_type(file_path)[0]
    files = {"logo-logo": (os.path.basename(file_path), picture, mime)}
    response = make_request(
        Method.POST, url, session=session, headers=headers, data=data,
        files=files)
    return response
savapi_client.py 文件源码 项目:do-portal 作者: certeu 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    p = argparse.ArgumentParser(
        description='SAVAPI Client',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    p.add_argument('--savapi-host', dest='host', help='SAVAPI service host',
                   default='127.0.0.1')
    p.add_argument('--savapi-port', dest='port', help='SAVAPI service port',
                   default=9999, type=int)
    p.add_argument('file', help='Absolute path of file')

    try:
        args = p.parse_args(argv[1:])
    except SystemExit:
        return 2

    log = logging.getLogger()
    log.addHandler(logging.StreamHandler())
    log.setLevel(logging.DEBUG)

    archive_mimes = ('application/zip', 'application/x-tar', 'application/rar')
    if magic:
        mime = magic.Magic(mime=True)
        mimetype = mime.from_file(args.file)
    else:
        mimes = MimeTypes()
        mimetype, _ = mimes.guess_type(args.file)

    with SAVAPIClient(args.host, args.port) as savapi:
        r = savapi.command('SET', 'PRODUCT', '10776')
        log.info(r)
        if mimetype in archive_mimes:
            r = savapi.command('SET', 'ARCHIVE_SCAN', '1')
            log.info(r)
        for r in savapi.scan(args.file):
            print('{} {} <<< {}'.format(r.code, r.definition, r.data))
            if int(r.code) in [319, 350]:
                savapi.command('QUIT')
emails.py 文件源码 项目:do-portal 作者: certeu 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def send_email(sender, recipients, subject, text_body, html_body=None,
               attach=None):
    msg = Message(subject, reply_to=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    if attach:
        mimes = MimeTypes()
        for file in attach:
            path_ = os.path.join(current_app.config['APP_UPLOADS'], file)
            with current_app.open_resource(path_) as fp:
                mime = mimes.guess_type(fp.name)
                msg.attach(file, mime[0], fp.read())
    mail.send(msg)
webcrawler.py 文件源码 项目:simple-web-crawler 作者: fikander 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def __init__(self, allowed_domains, depth_limit=1):
        super().__init__()
        self.allowed_domains = allowed_domains
        # allow local links
        self.allowed_domains.append('')
        self.mime = MimeTypes()
        # Queue implemented as dict as we need to store depth data alongside url
        self.queue = dict()  # { url: depth, .. }
        # TODO: make crawled a class
        self.crawled = dict()  # { url: {type: type, outlinks: {link: count, ..}}, .. }
        self.depth_limit = depth_limit
test_utils.py 文件源码 项目:peony-twitter 作者: odrling 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def builtin_mimetypes(func):

    @wraps(func)
    async def decorated(*args, **kwargs):
        with patch.object(utils, 'magic') as magic:
            magic.__bool__.return_value = False
            with patch.object(utils, 'mime') as mime:
                mime.guess_type.side_effect = mimetypes.MimeTypes().guess_type

                await func(*args, **kwargs)

    return decorated
feed.py 文件源码 项目:Quantrade 作者: quant-trade 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def item_enclosure_mime_type(self, item):
        mime = MimeTypes()
        try:
            if item.direction == 1:
                filename = join(self.folder, '{1}=={2}=={3}=={4}==longs.png'.format(\
                    item.broker.slug, item.symbol.symbol, item.period.period, item.system.title))
            elif item.direction == 2:
                filename = join(self.folder, '{1}=={2}=={3}=={4}==shorts.png'.format(\
                    item.broker.slug, item.symbol.symbol, item.period.period, item.system.title))

            mime_type = mime.guess_type(filename)[0]
            return mime_type
        except:
            return None
test_mimetypes.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def setUp(self):
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_encoding(self):
        getpreferredencoding = locale.getpreferredencoding
        self.addCleanup(setattr, locale, 'getpreferredencoding',
                                 getpreferredencoding)
        locale.getpreferredencoding = lambda: 'ascii'

        filename = support.findfile("mime.types")
        mimes = mimetypes.MimeTypes([filename])
        exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
                                          strict=True)
        self.assertEqual(exts, ['.g3', '.g\xb3'])
test_mimetypes.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def setUp(self):
        # ensure all entries actually come from the Windows registry
        self.original_types_map = mimetypes.types_map.copy()
        mimetypes.types_map.clear()
        mimetypes.init()
        self.db = mimetypes.MimeTypes()
feeds.py 文件源码 项目:QProb 作者: quant-trade 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def item_enclosure_mime_type(self, item):
        mime = MimeTypes()
        try:
            mime_type = mime.guess_type("{0}{1}".format(self.folder, item.image))[0]
            return mime_type
        except:
            return None
test_mimetypes.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def setUp(self):
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_registry_parsing(self):
        # the original, minimum contents of the MIME database in the
        # Windows registry is undocumented AFAIK.
        # Use file types that should *always* exist:
        eq = self.assertEqual
        mimetypes.init()
        db = mimetypes.MimeTypes()
        eq(db.guess_type("foo.txt"), ("text/plain", None))
        eq(db.guess_type("image.jpg"), ("image/jpeg", None))
        eq(db.guess_type("image.png"), ("image/png", None))
test_mimetypes.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def setUp(self):
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_registry_parsing(self):
        # the original, minimum contents of the MIME database in the
        # Windows registry is undocumented AFAIK.
        # Use file types that should *always* exist:
        eq = self.assertEqual
        mimetypes.init()
        db = mimetypes.MimeTypes()
        eq(db.guess_type("foo.txt"), ("text/plain", None))
        eq(db.guess_type("image.jpg"), ("image/jpeg", None))
        eq(db.guess_type("image.png"), ("image/png", None))
test_mimetypes.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def setUp(self):
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_encoding(self):
        getpreferredencoding = locale.getpreferredencoding
        self.addCleanup(setattr, locale, 'getpreferredencoding',
                                 getpreferredencoding)
        locale.getpreferredencoding = lambda: 'ascii'

        filename = support.findfile("mime.types")
        mimes = mimetypes.MimeTypes([filename])
        exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
                                          strict=True)
        self.assertEqual(exts, ['.g3', '.g\xb3'])
test_mimetypes.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def setUp(self):
        # ensure all entries actually come from the Windows registry
        self.original_types_map = mimetypes.types_map.copy()
        mimetypes.types_map.clear()
        mimetypes.init()
        self.db = mimetypes.MimeTypes()
validators.py 文件源码 项目:41Inc 作者: MikeShi42 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def validate_video_file(upload):
    """
    Validates uploaded file name by using mimetypes, part of Python standard
    library, to guess the mime type from the file extension.

    The file extension is not a reliable way to determine mime type. A better
    alternative is using the python-magic library, but that requires the
    libmagic library which is extra overhead, so not worth.
    """
    mime_type = mimetypes.MimeTypes().guess_type(upload.name)[0]
    if mime_type not in VIDEO_MIME_TYPES:
        raise ValidationError('File type not supported. MP4, Quicktime, or WebM recommended.')
test_mimetypes.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def setUp(self):
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_registry_parsing(self):
        # the original, minimum contents of the MIME database in the
        # Windows registry is undocumented AFAIK.
        # Use file types that should *always* exist:
        eq = self.assertEqual
        mimetypes.init()
        db = mimetypes.MimeTypes()
        eq(db.guess_type("foo.txt"), ("text/plain", None))
        eq(db.guess_type("image.jpg"), ("image/jpeg", None))
        eq(db.guess_type("image.png"), ("image/png", None))
test_mimetypes.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def setUp(self):
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_encoding(self):
        getpreferredencoding = locale.getpreferredencoding
        self.addCleanup(setattr, locale, 'getpreferredencoding',
                                 getpreferredencoding)
        locale.getpreferredencoding = lambda: 'ascii'

        filename = support.findfile("mime.types")
        mimes = mimetypes.MimeTypes([filename])
        exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
                                          strict=True)
        self.assertEqual(exts, ['.g3', '.g\xb3'])
test_mimetypes.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def setUp(self):
        # ensure all entries actually come from the Windows registry
        self.original_types_map = mimetypes.types_map.copy()
        mimetypes.types_map.clear()
        mimetypes.init()
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def setUp(self):
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def setUp(self):
        # ensure all entries actually come from the Windows registry
        self.original_types_map = mimetypes.types_map.copy()
        mimetypes.types_map.clear()
        mimetypes.init()
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def setUp(self):
        self.db = mimetypes.MimeTypes()
test_mimetypes.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 47 收藏 0 点赞 0 评论 0
def test_encoding(self):
        getpreferredencoding = locale.getpreferredencoding
        self.addCleanup(setattr, locale, 'getpreferredencoding',
                                 getpreferredencoding)
        locale.getpreferredencoding = lambda: 'ascii'

        filename = support.findfile("mime.types")
        mimes = mimetypes.MimeTypes([filename])
        exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
                                          strict=True)
        self.assertEqual(exts, ['.g3', '.g\xb3'])
test_mimetypes.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def setUp(self):
        # ensure all entries actually come from the Windows registry
        self.original_types_map = mimetypes.types_map.copy()
        mimetypes.types_map.clear()
        mimetypes.init()
        self.db = mimetypes.MimeTypes()


问题


面经


文章

微信
公众号

扫码关注公众号