• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python mimetypes.MimeTypes类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: upload_attachment

    def upload_attachment(self, file_path):
        __, file_name = os.path.split(file_path)
        mime = MimeTypes()
        url = urllib.pathname2url(file_path)
        mime_type, __ = mime.guess_type(url)

        data = {
            'file_name': file_name,
            'file_type': mime_type
        }
        url = urljoin(self.api_url, 'attachment/upload')
        response = self.post(url, data=data)

        with open(file_path) as fh:
            file_data = fh.read()

        upload_response = requests.put(
            response['upload_url'],
            data=file_data,
            headers={'content-type': mime_type},
            params={'file': file_path}
        )
        upload_response.raise_for_status()

        return {
            'file_url': response['file_url'],
            'file_type': mime_type,
        }
开发者ID:pyepye,项目名称:mondo-python,代码行数:28,代码来源:monzo.py


示例2: mime_type

 def mime_type(self):
     m = MimeTypes()
     m.read(LIASIS_DIR+MIME_TYPES)
     if m.guess_type(self.tfile):
         return m.guess_type(self.tfile)[0]
     else:
         return "text/plain"
开发者ID:dahabit,项目名称:liasis,代码行数:7,代码来源:server.py


示例3: get_mime_type

def get_mime_type(path):
    mime = MimeTypes()

    mime_type = mime.guess_type(path)[0]
    if not mime_type:
        mime_type = "text/{0}".format(os.path.splitext(path)[1])
    return mime_type
开发者ID:unfoldingWord-dev,项目名称:tools,代码行数:7,代码来源:file_utils.py


示例4: update_community

 def update_community(self, properties):
     pc = api.portal.get_tool('portal_catalog')
     brain = pc.unrestrictedSearchResults(portal_type='ulearn.community',
                                          community_hash=self.params['community'])
     if not brain:
         brain = pc.unrestrictedSearchResults(portal_type='ulearn.community',
                                              gwuuid=self.params['community'])
     if brain:
         community = brain[0].getObject()
         if properties['title'] is not None:
             community.title = properties['title']
         if properties['description'] is not None:
             community.description = properties['description']
         if properties['image'] is not None:
             imageObj = ''
             mime = MimeTypes()
             mime_type = mime.guess_type(properties['image'])
             imgName = (properties['image'].split('/')[-1]).decode('utf-8')
             imgData = requests.get(properties['image']).content
             imageObj = NamedBlobImage(data=imgData,
                                       filename=imgName,
                                       contentType=mime_type[0])
             community.image = imageObj
         if properties['activity_view'] is not None:
             community.activity_view = properties['activity_view']
         if properties['twitter_hashtag'] is not None:
             community.twitter_hashtag = properties['twitter_hashtag']
         if properties['notify_activity_via_push'] is not None:
             community.notify_activity_via_push = True if properties['notify_activity_via_push'] == 'True' else None
         if properties['notify_activity_via_push_comments_too'] is not None:
             community.notify_activity_via_push_comments_too = True if properties['notify_activity_via_push_comments_too'] == 'True' else None
         community.reindexObject()
         return True
     else:
         return False
开发者ID:UPCnet,项目名称:ulearn.core,代码行数:35,代码来源:communities.py


示例5: getMimeType

 def getMimeType(self,buffre,url,mtype):
     
     if '?' in url:
         url = url.split('?')[0]
         
     mime = MimeTypes()
     ext = os.path.splitext(url)[1]
     if mtype == 'text/html' and ext == '':
         if url[-1] == '/':
             l = len(url)-1
             
             url = url[0:-1]                         
         url = url+'/index.html'
         ext = '.html'
         
     #ext1 = mime.guess_extension(mtype,True)
     #print ext1
     mime_type = mime.guess_type(url)        
     #print url
     if ext:
         #print url
         u = urlparse.urlparse(url)
         #print u.netloc,u.path
         print self.host
         if self.host:
             root_dir = self.root_dir+"/"+self.host
             
         file_path = os.path.join(root_dir,u.netloc+u.path)
         print file_path
         #if not os.path.isfile(file_path):
         makeDir(os.path.dirname(file_path))
         f = open(file_path,"wb")            
         f.write(buffre)            
开发者ID:ptphp,项目名称:PtPy,代码行数:33,代码来源:pturllib.py


示例6: download

def download(request, filename):
    #down_file = File.objects.get(name = filename)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    DOWNLOAD_URL = BASE_DIR+"/download/"
    file_path = DOWNLOAD_URL + filename
    file_name = filename
    fp = open(file_path, 'rb')
    response = HttpResponse(fp.read())
    fp.close()
    mime = MimeTypes()
    type, encoding = mime.guess_type(file_name)
    if type is None:
        type = 'application/octet-stream'
    response['Content-Type'] = type
    response['Content-Length'] = str(os.stat(file_path).st_size)
    if encoding is not None:
        response['Content-Encoding'] = encoding
    if u'WebKit' in request.META['HTTP_USER_AGENT']:
        filename_header = 'filename=%s' % file_name.encode('utf-8')
    elif u'MSIE' in request.META['HTTP_USER_AGENT']:
        filename_header = ''
    else:
        filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(file_name.encode('utf-8'))
    response['Content-Disposition'] = 'attachment; ' + filename_header
    # 記錄系統事件
    if is_event_open(request) :       
        log = Log(user_id=request.user.id, event=u'下載檔案<'+filename+'>')
        log.save()     
    return response
开发者ID:jeankao,项目名称:scratch_old,代码行数:29,代码来源:views.py


示例7: GetRFC

def GetRFC(rfc_id,file_name,peer_ip,peer_port):
    global LRFCdata
    global Server
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(None)
    peer_ipaddr=peer_ip
    s.connect((peer_ipaddr,int(peer_port)))
    
    message = ["GETRFC",str(rfc_id),"P2P-DI/1.0","Host: ",IP,"Port: ",PORT,"Title: ",file_name,"Client ID: ",str(self_id)]
    s.send(pickle.dumps(message))

    os.chdir(os.getcwd())
    filename=file_name+".pdf"
    file1=open(filename,'wb')
    
    q=s.recv(4096)
    q=pickle.loads(q)
    
    if 'FILE NOT FOUND' in q:
        code = '404'
        phrase = 'FILE NOT FOUND'
        reply = ["P2P-DI/1.0 ",str(code),str(phrase)]
        PrintResponse(reply,'FILERESPN')
    else:
        if 'FILE FOUND' in q:
            last_modified = q[2]
            message = ["OK"]
            s.send(pickle.dumps(message))
            while True:
                q=s.recv(4096)
                if q:
                    file1.write(q)
                else:
                    code = '200'
                    phrase = 'OK'
                    mime = MimeTypes()
                    filesize = os.stat(filename).st_size
                    mime_type = mime.guess_type(filename)
                    reply = ["P2P-DI/1.0 ",str(code),str(phrase),"Last-Modified: ",str(last_modified),"Content-Length: ",str(filesize),"Content-Type: ",str(mime_type[0])]
                    PrintResponse(reply,'FILESENT')
                    file1.close()
                    break

            serverIP = Server[0]
            serverPort = Server[1]
            message=["PQUERY","P2P-DI/1.0 ",str(self_id),"Host: ",IP,"Port: ",str(PORT)]
            reply = client(message,serverIP,serverPort)
            PrintResponse(reply,'PQUERY')
            

            LocalRFC = LocalRFCRecord(rfc_id,file_name)
            LRFCdata.append(LocalRFC.getLocalRFC())
            Local_linked_list.append(LocalRFC.getLocalRFC())

            active_list = reply[4]    
            active_list=RFCStore(active_list,[[rfc_id,file_name]])
    
    s.close()
开发者ID:DoshiRonak,项目名称:Peer-to-Peer-File-sharing-using-DHT,代码行数:59,代码来源:client.py


示例8: export_warc

    def export_warc(self):
        # by using select_for_update and checking for existence of this file,
        # we make sure that we won't accidentally try to create the file multiple
        # times in parallel.
        asset = self.assets.select_for_update().first()
        if not asset:
            return  # this is not an old-style Link
        if default_storage.exists(self.warc_storage_file()):
            return

        guid = self.guid
        out = self.open_warc_for_writing()

        def write_resource_record(file_path, url, content_type):
            self.write_warc_resource_record(
                default_storage.open(file_path),
                url.encode('utf8'),
                content_type,
                default_storage.created_time(file_path),
                out)

        def write_metadata_record(metadata, target_headers):
            concurrent_to = (v for k, v in target_headers if k == warctools.WarcRecord.ID).next()
            warc_date = (v for k, v in target_headers if k == warctools.WarcRecord.DATE).next()
            url = (v for k, v in target_headers if k == warctools.WarcRecord.URL).next()
            self.write_warc_metadata_record(metadata, url, concurrent_to, warc_date, out)

        # write PDF capture
        if asset.pdf_capture and ('cap' in asset.pdf_capture or 'upload' in asset.pdf_capture):
            file_path = os.path.join(asset.base_storage_path, asset.pdf_capture)
            headers = write_resource_record(file_path, "file:///%s/%s" % (guid, asset.pdf_capture), 'application/pdf')
            #write_metadata_record({'role':'primary', 'user_upload':asset.user_upload}, headers)

        # write image capture (if it's not a PDF thumbnail)
        elif (asset.image_capture and ('cap' in asset.image_capture or 'upload' in asset.image_capture)):
            file_path = os.path.join(asset.base_storage_path, asset.image_capture)
            mime_type = get_mime_type(asset.image_capture)
            write_resource_record(file_path, "file:///%s/%s" % (guid, asset.image_capture), mime_type)

        if asset.warc_capture:
            # write WARC capture
            if asset.warc_capture == 'archive.warc.gz':
                file_path = os.path.join(asset.base_storage_path, asset.warc_capture)
                self.write_warc_raw_data(default_storage.open(file_path), out)

            # write wget capture
            elif asset.warc_capture == 'source/index.html':
                mime = MimeTypes()
                for root, dirs, files in default_storage.walk(os.path.join(asset.base_storage_path, 'source')):
                    rel_path = root.split(asset.base_storage_path, 1)[-1]
                    for file_name in files:
                        mime_type = mime.guess_type(file_name)[0]
                        write_resource_record(os.path.join(root, file_name),
                                              "file:///%s%s/%s" % (guid, rel_path, file_name), mime_type)

        self.close_warc_after_writing(out)

        # regenerate CDX index
        self.cdx_lines.all().delete()
开发者ID:jcushman,项目名称:perma,代码行数:59,代码来源:models.py


示例9: configure_mimetypes

def configure_mimetypes(extra_types):
    """
    Add additional mimetypes to a local MimeTypes instance to avoid polluting
    global registery
    """
    mimetypes = MimeTypes()
    for content_type, extension in extra_types:
        mimetypes.add_type(content_type, extension)
    return mimetypes
开发者ID:Vendetta131,项目名称:Django,代码行数:9,代码来源:base.py


示例10: searchImages

def searchImages(rootDir):
    imageList = []
    mime = MimeTypes()
    for root, subFolders, files in os.walk(rootDir):
        for file in files:
            mt = mime.guess_type(file)[0]
            if mt and mt.startswith('image/'):
                imageList = imageList + [os.path.join(root,file)]
    return imageList
开发者ID:andoniu,项目名称:dupImg,代码行数:9,代码来源:dup_img.py


示例11: get_extension

def get_extension(url):
    from mimetypes import MimeTypes
    mime_types = MimeTypes()

    (type, encoding) = mime_types.guess_type(url)
    extensions = mime_types.guess_all_extensions(type)
    extension = extensions[-1]

    return extension
开发者ID:liuxue0905,项目名称:GoldenTimes,代码行数:9,代码来源:util.py


示例12: add_documents

def add_documents(request, category_id):
    if request.is_ajax():
        files = request.GET.getlist('files', False)
        cat = Category.objects.get(id=category_id)
        l_doc = []
        l_pdf = []
        cmds = []
        paths = []
        for f in list(files):
            mime = MimeTypes()
            path = os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_DIR, f)
            m = mime.guess_type(path)[0]
            d = Document(name=f.encode('ascii', 'ignore'), owner=request.user, refer_category=cat)
            d.save()
            cat.add_doc(d)
            if m == 'application/pdf':
                l_pdf.append(([cat], path, f, [d]))
            elif m in ['image/png', 'image/jpeg', 'image/bmp']:
                im = Image.open(path)
                w, h = im.size
                new_filename = str(d.id) + '_' + f
                new_path = os.path.join(cat.get_absolute_path(), new_filename)
                shutil.copy2(path, new_path)
                d.add_page(d.get_npages() + 1, new_filename, w, h)
                for fu in FileUpload.objects.all():
                    if fu.file.path == path:
                        fu.delete()
                d.complete = True
                d.save()
                remove_fileupload([path])
            elif m in ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']:
                p = re.compile(r'.[Dd][Oo][Cc][xX]?$')
                new_f = p.sub('.pdf', f)
                new_path = path.replace(f, new_f)
                cmd = 'soffice --headless --convert-to pdf  %s --outdir %s/upload' % (path, settings.MEDIA_ROOT)
                cmds.append(cmd)
                paths.append(path)
                l_doc.append(([cat], new_path, new_f, [d]))
            elif m in ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']:
                p = re.compile(r'.[Xx][Ll][Ss][xX]?$')
                new_f = p.sub('.pdf', f)
                new_path = path.replace(f, new_f)
                cmd = 'soffice --headless --convert-to pdf  %s --outdir %s/upload' % (path, settings.MEDIA_ROOT)
                cmds.append(cmd)
                paths.append(path)
                l_doc.append(([cat], new_path, new_f, [d]))
            else:
                print 'ERREUR FORMAT FICHIER'
        if len(l_doc):
            thread1 = Timer(0, manage_convert_doc_to_pdf, (cmds, paths, l_doc,))
            thread1.start()
        if len(l_pdf):
            thread = Timer(0, manage_convert_pdf_to_jpg, (l_pdf,))
            thread.start()
        results = {'doc_list': [d.as_json() for d in cat.get_docs()], 'n': cat.count_docs()}
        return HttpResponse(json.dumps(results))
开发者ID:Foxugly,项目名称:MyTaxAccountant,代码行数:56,代码来源:views.py


示例13: mime

 def mime(self):
     if self.mMimeType is not None:
         return self.mMimeType
     
     mime = MimeTypes()
     url = urllib.pathname2url(self.mFullPathName)
     self.mMimeType = mime.guess_type(url)[0]
     if self.mMimeType is None:
         self.mMimeType = "Unkown/None"
     return self.mMimeType
开发者ID:huangxiaohu1986,项目名称:PythonTools,代码行数:10,代码来源:MyFile.py


示例14: showfile

def showfile(file):
    mime = MimeTypes()
    mime_type = mime.guess_type(file)
    if mime_type[0] is not None and mime_type[0].startswith("image"):
        return render_template("image.html",
                title="pyle :: preview",
                filepath="/data/" + file,
                filename=os.path.basename(file))
    else:
        return readfile(file)
开发者ID:hrkfdn,项目名称:pyle,代码行数:10,代码来源:pyle.py


示例15: show_media

 def show_media(self, url, title = "", desc ="", loop = 0):
     mime = MimeTypes()
     mime_type = mime.guess_type(url)
     payload = {
         "target": url,
         "title":title,
         "description":desc,
         "mimeType": mime_type[0],
         "iconSrc":"",
         "loop":loop}
     command = '{"id":"images","type":"request","uri":"ssap://media.viewer/open","payload":'+ json.dumps(payload)+'}'
     self.send_command(command)
开发者ID:Bonze255,项目名称:lgwebos,代码行数:12,代码来源:__init__.py


示例16: transform_import_values

    def transform_import_values(self, value):
        '''
        # TODO: Following commented code can be used if user does not already have file in final location using django ORM:

        request = HttpRequest()
        # request.FILES['file-list_' + str(nodeid)] = None
        files = []
        # request_list = []

        for val in value.split(','):
            val_dict = {}
            val_dict['content'] = val
            val_dict['name'] = val.split('/')[-1].split('.')[0]
            val_dict['url'] = None
            # val_dict['size'] = None
            # val_dict['width'] = None
            # val_dict['height'] = None
            files.append(val_dict)
            f = open(val, 'rb')
            django_file = InMemoryUploadedFile(f,'file',val.split('/')[-1].split('.')[0],None,None,None)
            request.FILES.appendlist('file-list_' + str(nodeid), django_file)
        print request.FILES
        value = files
        '''

        mime = MimeTypes()
        tile_data = []
        for file_path in value.split(','):
            try:
                file_stats = os.stat(file_path)
                tile_file['lastModified'] = file_stats.st_mtime
                tile_file['size'] =  file_stats.st_size
            except:
                pass
            tile_file = {}
            tile_file['file_id'] =  str(uuid.uuid4())
            tile_file['status'] = ""
            tile_file['name'] =  file_path.split('/')[-1]
            tile_file['url'] =  settings.MEDIA_URL + 'uploadedfiles/' + str(tile_file['name'])
            # tile_file['index'] =  0
            # tile_file['height'] =  960
            # tile_file['content'] =  None
            # tile_file['width'] =  1280
            # tile_file['accepted'] =  True
            tile_file['type'] =  mime.guess_type(file_path)[0]
            tile_file['type'] = '' if tile_file['type'] == None else tile_file['type']
            tile_data.append(tile_file)
            file_path = 'uploadedfiles/' + str(tile_file['name'])
            fileid = tile_file['file_id']
            models.File.objects.get_or_create(fileid=fileid, path=file_path)

        result = json.loads(json.dumps(tile_data))
        return result
开发者ID:mradamcox,项目名称:arches,代码行数:53,代码来源:datatypes.py


示例17: addFileOutput

	def addFileOutput(self, name, filepath):
		data = open(filepath).read()
		filename = os.path.basename(filepath)
		mime = MimeTypes()
		mime_guess = mime.guess_type(filename)[0]

		self.result[name] = {
			"filename": filename,
			"content-type": mime_guess,
			"data": base64.b64encode(data)
		}
		return self
开发者ID:ArcherSys,项目名称:Peridot,代码行数:12,代码来源:__init__.py


示例18: get_mime_type

    def get_mime_type(self, file_path):
        #Get mime type
        try:
            mime = MimeTypes()
            murl = urllib.pathname2url(file_path)
            mime_type = mime.guess_type(murl)[0]
            if mime_type == None:
                mime_type = 'text/plain'
        except:
            mime_type = 'text/plain'

        return mime_type
开发者ID:UstadMobile,项目名称:exelearning-ustadmobile-work,代码行数:12,代码来源:resumablejsclient.py


示例19: update_data

    def update_data(self, data, content_type, size):
        """

        """
        if not data:
            # still index
            self.index_object()
            return

        passed, virus_name = DataVirusCheckAdapter(data).process()

        if not passed:
            log.warn('found virus %s, rejecting file' % virus_name)
            raise XWFFileError('found virus %s, rejecting file' % virus_name)

        # this isn't necessarily an error, on init we get called without data
        base_files_dir = self._base_files_dir
        self.size = size
        self.set_modificationTime()

        if base_files_dir:
            fileId = os.path.join(base_files_dir, self.getId())
            f = file(fileId, 'wb+')

            if hasattr(data, '__class__') and data.__class__ is Pdata:
                while data is not None:
                    f.write(data.data)
                    data = data.next
            else:
                f.write(data)

            f.close()

        # fix the title
        title = to_unicode_or_bust(self.title)
        title = removePathsFromFilenames(title)
        self.title = title

        if content_type is not None:
            self.content_type = content_type
        else:
            mtypes = MimeTypes()
            mime_type = mtypes.guess_type(title)
            if mime_type:
                self.content_type = mime_type

        self.ZCacheable_invalidate()
        self.ZCacheable_set(None)
        self.http__refreshEtag()

        # index ourselves into the catalog
        self.index_object()
开发者ID:groupserver,项目名称:Products.XWFFileLibrary2,代码行数:52,代码来源:XWFFile2.py


示例20: get_base64_image

def get_base64_image(url):
    template_image = ''
    mime = MimeTypes()
    mime_type = mime.guess_type(url)[0]
    # Steam the image from the url
    request = requests.get(url)
    image_buffer = StringIO(request.content)

    if image_buffer:
        template_image = image_buffer.getvalue().encode('base64')
        template_image = u'data:%s;base64,%s' % (mime_type, template_image)

    return template_image
开发者ID:pomahtuk,项目名称:stonegarant,代码行数:13,代码来源:helpres.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python core.MimicCore类代码示例发布时间:2022-05-27
下一篇:
Python mimetypes.MIMEType类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap