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


Python MimeTypes.guess_extension方法代码示例

本文整理汇总了Python中mimetypes.MimeTypes.guess_extension方法的典型用法代码示例。如果您正苦于以下问题:Python MimeTypes.guess_extension方法的具体用法?Python MimeTypes.guess_extension怎么用?Python MimeTypes.guess_extension使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mimetypes.MimeTypes的用法示例。


在下文中一共展示了MimeTypes.guess_extension方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _getExtension

# 需要导入模块: from mimetypes import MimeTypes [as 别名]
# 或者: from mimetypes.MimeTypes import guess_extension [as 别名]
def _getExtension( episode ):
	# get extension from url
	urlExt = os.path.splitext( episode.url )[ 1 ]
	# get extension from media type
	mime = MimeTypes()
	mimeExtList = mime.guess_all_extensions( episode.type )
	# check if url extension matches any item in list
	if urlExt in mimeExtList:
		# yep, then url extension is good
		return urlExt
	# otherwise, use recommendation from MimeTypes, as default we use .mp3  	
	mimeExt = mime.guess_extension( episode.type )
	if mimeExt == None:
		mimeExt = ".mp3"
	return mimeExt
开发者ID:fredrander,项目名称:podagg,代码行数:17,代码来源:podfile.py

示例2: upload_file

# 需要导入模块: from mimetypes import MimeTypes [as 别名]
# 或者: from mimetypes.MimeTypes import guess_extension [as 别名]
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():

            mime = MimeTypes()
            uploaded_file = request.FILES['file']
            mime_type = mime.guess_type(uploaded_file.name)

            # Get mime type string from tuple
            if mime_type[0]:
                mime_type = mime_type[0]
            else:
                return HttpResponseBadRequest(json.dumps({'status':'failed', 'reason':'Invalid file.'}), 'application/json')

            if validate_upload_file(uploaded_file, mime_type) and uploaded_file.size <= settings.MAX_ARCHIVE_FILE_SIZE:
                link = Link(submitted_url=form.cleaned_data['url'], submitted_title=form.cleaned_data['title'], created_by = request.user)
                link.save()

                asset = Asset(link=link)
                file_name = 'cap' + mime.guess_extension(mime_type)
                file_path = os.path.join(asset.base_storage_path, file_name)

                uploaded_file.file.seek(0)
                file_name = default_storage.store_file(uploaded_file, file_path)

                if mime_type == 'application/pdf':
                    asset.pdf_capture = file_name
                else:
                    asset.image_capture = file_name
                asset.save()

                response_object = {'status':'success', 'linky_id':link.guid, 'linky_hash':link.guid}

                return HttpResponse(json.dumps(response_object), 'application/json', 201)  # '201 Created' status
            else:
                return HttpResponseBadRequest(json.dumps({'status':'failed', 'reason':'Invalid file.'}), 'application/json')
        else:
            return HttpResponseBadRequest(json.dumps({'status':'failed', 'reason':'Missing file.'}), 'application/json')

    return HttpResponseBadRequest(json.dumps({'status':'failed', 'reason':'No file submitted.'}), 'application/json')
开发者ID:allmende,项目名称:perma,代码行数:43,代码来源:link_management.py

示例3: forge_email

# 需要导入模块: from mimetypes import MimeTypes [as 别名]
# 或者: from mimetypes.MimeTypes import guess_extension [as 别名]

#.........这里部分代码省略.........
    @return: forged email as an EmailMessage object"""
    from invenio_ext.template import render_template_to_string

    ln = default_ln(ln)
    if html_images is None:
        html_images = {}

    content = render_template_to_string('mail_text.tpl',
                                        content=unicodifier(content),
                                        header=unicodifier(header),
                                        footer=unicodifier(footer)
                                        ).encode('utf8')

    if isinstance(toaddr, list):
        toaddr = ','.join(toaddr)

    if isinstance(bccaddr, list):
        bccaddr = ','.join(bccaddr)

    if isinstance(replytoaddr, list):
        replytoaddr = ','.join(replytoaddr)

    toaddr = remove_temporary_emails(toaddr)

    headers = {}
    kwargs = {'to': [], 'cc': [], 'bcc': []}

    if replytoaddr:
        headers['Reply-To'] = replytoaddr
    if usebcc:
        headers['Bcc'] = bccaddr
        kwargs['bcc'] = toaddr.split(',') + bccaddr.split(',')
        kwargs['to'] = ['Undisclosed.Recipients:']
    else:
        kwargs['to'] = toaddr.split(',')
    headers['From'] = fromaddr
    headers['Date'] = formatdate(localtime=True)
    headers['User-Agent'] = 'Invenio %s at %s' % (cfg['CFG_VERSION'],
                                                  cfg['CFG_SITE_URL'])

    if html_content:
        html_content = render_template_to_string(
            'mail_html.tpl',
            content=unicodifier(html_content),
            header=unicodifier(html_header),
            footer=unicodifier(html_footer)
        ).encode('utf8')

        msg_root = EmailMultiAlternatives(subject=subject, body=content,
                                          from_email=fromaddr,
                                          headers=headers, **kwargs)
        msg_root.attach_alternative(html_content, "text/html")

        # if not html_images:
        #    # No image? Attach the HTML to the root
        #    msg_root.attach(msg_text)
        # else:
        if html_images:
            # Image(s)? Attach the HTML and image(s) as children of a
            # "related" block
            msg_related = MIMEMultipart('related')
            # msg_related.attach(msg_text)
            for image_id, image_path in iteritems(html_images):
                attach_embed_image(msg_related, image_id, image_path)
            msg_root.attach(msg_related)
    else:
        msg_root = EmailMessage(subject=subject, body=content,
                                from_email=fromaddr, headers=headers, **kwargs)

    if attachments:
        _mimes = MimeTypes(strict=False)
        for attachment in attachments:
            try:
                mime = None
                if type(attachment) in (list, tuple):
                    attachment, mime = attachment
                if mime is None:
                    # Automatic guessing of mimetype
                    mime = _mimes.guess_type(attachment)[0]
                if mime is None:
                    ext = _mimes.guess_extension(getContentType(attachment))
                    mime = _mimes.guess_type("foo" + ext)[0]
                if not mime:
                    mime = 'application/octet-stream'
                part = MIMEBase(*mime.split('/', 1))
                part.set_payload(open(attachment, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition',
                    'attachment; filename="%s"' %
                    os.path.basename(attachment))
                msg_root.attach(part)
            except:
                from invenio_ext.logging import register_exception
                register_exception(
                    alert_admin=True,
                    prefix="Can't attach %s" %
                    attachment)

    return msg_root
开发者ID:jalavik,项目名称:invenio-ext,代码行数:104,代码来源:__init__.py

示例4: upload_file

# 需要导入模块: from mimetypes import MimeTypes [as 别名]
# 或者: from mimetypes.MimeTypes import guess_extension [as 别名]
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            
            mime = MimeTypes()
            mime_type = mime.guess_type(request.FILES['file'].name)
            
            # Get mime type string from tuple
            if mime_type[0]:
                mime_type = mime_type[0]
            else:
                return HttpResponseBadRequest(json.dumps({'status':'failed', 'reason':'Invalid file.'}), 'application/json')
            

            if validate_upload_file(request.FILES['file'], mime_type) and request.FILES['file'].size <= settings.MAX_ARCHIVE_FILE_SIZE:
                link = Link(submitted_url=form.cleaned_data['url'], submitted_title=form.cleaned_data['title'])
                
                if request.user.is_authenticated():
                    link.created_by = request.user
                link.save()
                
                now = dt = datetime.now()
                time_tuple = now.timetuple()
                path_elements = [str(time_tuple.tm_year), str(time_tuple.tm_mon), str(time_tuple.tm_mday), str(time_tuple.tm_hour), str(time_tuple.tm_min), link.guid]

                linky_home_disk_path = settings.GENERATED_ASSETS_STORAGE + '/' + os.path.sep.join(path_elements)

                if not os.path.exists(linky_home_disk_path):
                    os.makedirs(linky_home_disk_path)

                asset, created = Asset.objects.get_or_create(link=link)
                asset.base_storage_path = os.path.sep.join(path_elements)
                asset.save()

                file_name = '/cap' + mime.guess_extension(mime_type)

                if mime_type == 'application/pdf':
                    asset.pdf_capture = file_name
                else:
                    asset.image_capture = file_name

                    #print linky_home_disk_path + file_name
                    #png = PythonMagick.Image(linky_home_disk_path + file_name)
                    #png.write("file_out.png")
                    #params = ['convert', linky_home_disk_path + file_name, 'out.png']
                    #subprocess.check_call(params)

                asset.save()
                
                request.FILES['file'].file.seek(0)
                f = open(linky_home_disk_path + file_name, 'w')
                f.write(request.FILES['file'].file.read())
                os.fsync(f)
                f.close()

                response_object = {'status':'success', 'linky_id':link.guid, 'linky_hash':link.guid}

                """try:
                    get_source.delay(link.guid, target_url, os.path.sep.join(path_elements), request.META['HTTP_USER_AGENT'])
                    store_text_cap.delay(target_url, target_title, asset)
                except Exception, e:
                    # TODO: Log the failed url
                    asset.pdf_capture = 'failed'
                    asset.save()"""

                return HttpResponse(json.dumps(response_object), 'application/json')
            else:
                return HttpResponseBadRequest(json.dumps({'status':'failed', 'reason':'Invalid file.'}), 'application/json')
        else:
            return HttpResponseBadRequest(json.dumps({'status':'failed', 'reason':'Missing file.'}), 'application/json')
开发者ID:aekblaw,项目名称:perma,代码行数:73,代码来源:api.py


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