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


Python mimetypes.guess_type函数代码示例

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


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

示例1: get_file_name_mime

	def get_file_name_mime(self, url):
		pgctnt, hName, mime = self.wg.getFileNameMime(url)

		parsed = urllib.parse.urlparse(url)
		pathname = os.path.split(parsed.path)[-1]
		if not hName and not mime and not pathname:
			self.log.error("cannot figure out content type for url: %s", url)
			return pgctnt, "unknown.unknown", "application/octet-stream"

		# empty path with mimetype of text/html generally means it's a directory index (or some horrible dynamic shit).
		if not hName and not pathname and mime == "text/html":
			self.log.info("No path and root location. Assuming index.html")
			return pgctnt, "index.html", "text/html"

		ftype, guessed_mime = mimetypes.guess_type(hName)
		if ftype:
			return pgctnt, hName, guessed_mime if not mime else mime

		ftype, guessed_mime = mimetypes.guess_type(pathname)
		if ftype:
			return pgctnt, pathname, guessed_mime if not mime else mime

		chunks = [hName, pathname]
		chunks = [chunk for chunk in chunks if chunk]

		outname = " - ".join(chunks)
		if mime and mimetypes.guess_extension(mime):
			newext = mimetypes.guess_extension(mime)
		else:
			newext = ".unknown"

		if not outname:
			outname = "unknown"
		return pgctnt, outname+newext, mime if mime else "application/octet-stream"
开发者ID:fake-name,项目名称:ReadableWebProxy,代码行数:34,代码来源:RawEngine.py

示例2: _upload_plot

def _upload_plot(client, bucket, plot):

    extra_args = dict(ACL='public-read')
    url_template = '//{0}.s3.amazonaws.com/{1}/{2}/{3}'

    with DirectoryContext(plot.directory) as dir_ctx:
        try:
            extra_args['ContentType'] = mime.guess_type(plot.content)[0]
            client.upload_file(plot.content, bucket,
                               path.join(plot.plot_id, plot.version, plot.content),
                               ExtraArgs=extra_args)

            extra_args['ContentType'] = mime.guess_type(plot.thumbnail)[0]
            client.upload_file(plot.thumbnail, bucket,
                               path.join(plot.plot_id, plot.version, plot.thumbnail),
                               ExtraArgs=extra_args)

            if path.exists('resources'):
                for dir_path, subdir_list, file_list in walk('resources'):
                    for fname in file_list:
                        full_path = path.join(dir_path, fname)
                        extra_args['ContentType'] = mime.guess_type(full_path)[0]
                        client.upload_file(full_path, bucket,
                                           path.join(plot.plot_id, plot.version, full_path),
                                           ExtraArgs=extra_args)

            results = [url_template.format(bucket, plot.plot_id, plot.version, plot.content),
                       url_template.format(bucket, plot.plot_id, plot.version, plot.thumbnail)]

            return pd.Series(results)

        except botocore.exceptions.ClientError as e:
            print(e.response)
            return False
开发者ID:MattHJensen,项目名称:plots,代码行数:34,代码来源:cli.py

示例3: put

 def put(self, file='', content_type='', content_enc='',
         isbin=re.compile(r'[\000-\006\177-\277]').search,
         **kw):
     headers = self.__get_headers(kw)
     filetype = type(file)
     if filetype is type('') and (isbin(file) is None) and \
        os.path.exists(file):
         ob = open(file, 'rb')
         body = ob.read()
         ob.close()
         c_type, c_enc = guess_type(file)
     elif filetype is FileType:
         body = file.read()
         c_type, c_enc = guess_type(file.name)
     elif filetype is type(''):
         body = file
         c_type, c_enc = guess_type(self.url)
     else:
         raise ValueError, 'File must be a filename, file or string.'
     content_type = content_type or c_type
     content_enc = content_enc or c_enc
     if content_type: headers['Content-Type'] = content_type
     if content_enc:  headers['Content-Encoding'] = content_enc
     headers['Content-Length'] = str(len(body))
     return self.__snd_request('PUT', self.uri, headers, body)
开发者ID:cwt,项目名称:boa-constructor,代码行数:25,代码来源:client.py

示例4: get_detail

    def get_detail(self, request, **kwargs):
        """
        Returns a single serialized resource.
        Calls ``cached_obj_get/obj_get`` to provide the data, then handles that result
        set and serializes it.
        Should return a HttpResponse (200 OK).
        Guess the mimetype of the file and return it as an attachment object
        """

        basic_bundle = self.build_bundle(request=request)

        obj = self.obj_get(basic_bundle, **kwargs)

        bundle = self.build_bundle(obj=obj, request=request)
        bundle = self.full_dehydrate(bundle)
        bundle = self.alter_detail_data_to_serialize(request, bundle)

        #return our response here
        #get extension from the FlowFile object
        #match this to a dictionary of mimetypes with extensions
        fb = obj.file.read()
        mimetype = mimetypes.guess_type(obj.full_path)[0]
        #if mimetype.index('spreadsheetml') > 0:
        
        response = http.HttpResponse(fb, content_type=mimetypes.guess_type(obj.full_path)[0])
        #if it's not an image, it is a download link - add the necessary content disposition info
        if(mimetype.count('image') == 0):
            response['Content-Disposition'] = 'attachment; filename=%s' % obj.original_filename
        return response
开发者ID:thesgc,项目名称:chembiohub_ws,代码行数:29,代码来源:views.py

示例5: _get_resource

def _get_resource(resource_url: str) -> (str, bytes):
    """Download or reads a file (online or local).

    Parameters:
        resource_url (str): URL or path of resource to load
    Returns:
        str, bytes: Tuple containing the resource's MIME type and its data.
    Raises:
        NameError: If an HTTP request was made and ``requests`` is not available.
        ValueError: If ``resource_url``'s protocol is invalid.
    """
    url_parsed = urlparse(resource_url)
    if url_parsed.scheme in ['http', 'https']:
        # Requests might not be installed
        if requests_get is not None:
            request = requests_get(resource_url)
            data = request.content
            if 'Content-Type' in request.headers:
                mimetype = request.headers['Content-Type']
            else:
                mimetype = mimetypes.guess_type(resource_url)
        else:
            raise NameError("HTTP URL found but requests not available")
    elif url_parsed.scheme == '':
        # '' is local file
        with open(resource_url, 'rb') as f:
            data = f.read()
        mimetype, _ = mimetypes.guess_type(resource_url)
    elif url_parsed.scheme == 'data':
        raise ValueError("Resource path is a data URI", url_parsed.scheme)
    else:
        raise ValueError("Not local path or HTTP/HTTPS URL", url_parsed.scheme)

    return mimetype, data
开发者ID:BitLooter,项目名称:htmlark,代码行数:34,代码来源:htmlark.py

示例6: movieView

def movieView(request,id,movie):
	feature=get_object_or_404(CaseFeature, case__pk=id, name='MovieGallery')
	path=feature.getMoviePath(movie)
	print mimetypes.guess_type(path)[0]
	response=HttpResponse(FileWrapper(open(path)), content_type=mimetypes.guess_type(path)[0])
	response['Content-Length']=os.path.getsize(path)
	return response
开发者ID:irvined1982,项目名称:percyval,代码行数:7,代码来源:views.py

示例7: push_file

 def push_file(self, pfile, body=None, file_type=None, file_name=None):
     # FP
     if not isinstance(pfile, str):
         if os.fstat(pfile.fileno()).st_size > self.UPLOAD_LIMIT:
             return 'File too big'
         if not file_type:
             file_type, __ = mimetypes.guess_type(pfile.name)
         if not file_name:
             file_name = pfile.name
         payload = {'file_type': file_type,
                    'file_name': file_name}
         r = self._s.get(self.UPLOAD_URL, params=payload)
         _pushbullet_responses(r)
         file_url = r.json()['file_url']
         upload_url = r.json()['upload_url']
         data = r.json()['data']
         files = {'file': pfile}
         _pushbullet_responses(requests.post(upload_url, files=files, data=data))
     # String/url
     else:
         if not file_type:
             file_type, __ = mimetypes.guess_type(pfile)
         if not file_name:
             __, file_name = pfile.rsplit('/', 1)
         file_url = pfile
     data = {'type': 'file',
             'file_type': file_type,
             'file_name': file_name,
             'file_url': file_url,
             'body': body}
     return self._push(data)
开发者ID:Spittie,项目名称:yapbl.py,代码行数:31,代码来源:yapbl.py

示例8: save_uploaded

def save_uploaded():
	fname, content = get_uploaded_content()
	print mimetypes.guess_type(content)
	if content:
		return save_file(fname, content);
	else:
		raise Exception
开发者ID:pawaranand,项目名称:phr,代码行数:7,代码来源:uploader.py

示例9: create_file_message

def create_file_message(recipient_address, *args):
    """ Creates a Python email with file attachments as part of a
    MIME-class message.
    :param recipient_address: Email address of the recipient
    :param *args: List parameter containing filenames
    :return: MIMEMultipart instance
    """
    
    message = MIMEMultipart()
    message["to"] = recipient_address
    
    # Only attach image, plain and html text file types, according to the
    # first element of mimetypes' guess_type method
    for fn in args:
        fn = os.path.normpath(fn)
        
        if not mimetypes.guess_type(fn)[0]:
            continue
        
        if mimetypes.guess_type(fn)[0].find("image") >= 0:
            with open(fn, "rb") as f:
                message.attach(MIMEImage(f.read()))
            
        elif mimetypes.guess_type(fn)[0].find("plain") >= 0:
            with open(fn, "r") as f:
                message.attach(MIMEText(f.read(), "plain"))
                
        elif mimetypes.guess_type(fn)[0].find("html") >= 0:
            with open(fn, "r") as f:
                message.attach(MIMEText(f.read(), "html"))
                
    return message
开发者ID:Astrocesped,项目名称:OST_Homework,代码行数:32,代码来源:email_parser.py

示例10: theme_create_static_file

def theme_create_static_file(request, name):
    theme = get_object_or_404(Theme, name=name)
    ret = {}

    if request.method == 'POST':
        name = request.POST['name']
        if theme.static_files.filter(name=name).count():
            ret = {'result':'error', 'message':'Static File already exists.'}
        else:
            sf = theme.static_files.create(name=name)

            if request.POST.get('url', None):
                sf.url = request.POST['url']
                sf.mime_type = mimetypes.guess_type(sf.url)[0] or ''
                sf.save()
            else:
                # Saves an empty file as a starting point
                file_name = '%s-%s-%s'%(theme.pk, sf.pk, name)
                content = ContentFile('')
                sf.file.save(file_name, content)

                # Detects the mimetype for the given name
                sf.mime_type = mimetypes.guess_type(file_name)[0] or ''
                sf.save()
            ret = {'result':'ok', 'info':{'pk':sf.pk, 'url':sf.get_url()}}

    return HttpResponse(simplejson.dumps(ret), mimetype='text/javascript')
开发者ID:brunogola,项目名称:django-themes,代码行数:27,代码来源:views.py

示例11: _get_rss_item

def _get_rss_item(page):
    labels = get_page_labels(page)
    if "draft" in labels or "queue" in labels:
        return ""
    if "date" not in page:
        return ""

    xml = u"<item>\n"
    xml += u"\t<title>%s</title>\n" % _escape_xml(page["title"])
    xml += u"\t<guid>%s</guid>\n" % _full_url(page["url"])
    xml += u"\t<pubDate>%s</pubDate>\n" % _format_rfc_date(page["date"])

    if "file" in page:
        _filename = page["file"].split("/")[-1]
        mime_type = mimetypes.guess_type(_filename)[0]
        xml += u"\t<enclosure url='%s' type='%s' length='%s'/>\n" % (page["file"], mime_type, page.get("filesize", "0"))

    if "illustration" in page:
        _filename = page["illustration"].split("/")[-1]
        mime_type = mimetypes.guess_type(_filename)[0]
        xml += u"\t<enclosure url='%s' type='%s' length='%s'/>\n" % (page["illustration"], mime_type, 0)

    if get_config("rss_with_bodies") != False:
        xml += u"\t<description>%s</description>\n" % _escape_xml(_fix_rss_item_description(page.html, page))

    author = get_page_author(page)
    if author is not None:
        xml += u"\t<author>%s</author>\n" % author.get("email", "[email protected]")

    xml += u"</item>\n"
    return xml
开发者ID:Chaepitie,项目名称:tmradio-website,代码行数:31,代码来源:macros.py

示例12: TextFileChecker

def TextFileChecker(FileFolder, FileName):
    FileCheck = False
        
    if (mimetypes.guess_type(FileFolder + FileName)[0] == 'text/plain') or (mimetypes.guess_type(FileFolder + FileName)[0] == 'application/x-ns-proxy-autoconfig') or (mimetypes.guess_type(FileFolder + FileName)[0] == None):
        FileCheck = True

    return FileCheck
开发者ID:Delosari,项目名称:pyResources,代码行数:7,代码来源:vitools.py

示例13: add_image_set_by_array

def add_image_set_by_array(images, parents, name):
    # check for duplicate name
    if db.images.find_one({'name': name}) != None:
        raise ValueError(('An image set with the name %s already exists. Please ' +
                         'change the folder name and try uploading again.') % name)

    # put all the parent images into gridFS, save their object IDs
    parent_list = []
    for image in parents:
        with open(image, 'rb') as f:
            data = f.read()
            content_type = guess_type(image)[0]
            if content_type == None:
                raise TypeError(('Couldn\'t guess the file extension for %s. ' +
                                 'Check the filename.') % image)
            parent_id = fs.put(data, content_type=content_type)
            parent_list.append(parent_id)

    # put all the images into gridFS, save their object IDs
    image_list = []
    for image in images:
        with open(image['path'], 'rb') as f:
            data = f.read()
            content_type = guess_type(image['path'])[0]
            if content_type == None:
                raise TypeError(('Couldn\'t guess the file extension for %s. ' +
                                 'Check the filename.') % image['path'])
            image_id = fs.put(data, content_type=content_type)
            image_list.append({'image_id': image_id, 'parent': parent_list[image['category']], 'category': image['category']})

    # save the image set, return the 
    return db.images.insert({'name': name,
                             'parents': parent_list,
                             'images': image_list})
开发者ID:tbohlen,项目名称:human-gibbs,代码行数:34,代码来源:db.py

示例14: clean_file

	def clean_file(self):
		data = self.cleaned_data['file']
		task = self.cleaned_data['solution'].task
		max_file_size_kb = task.max_file_size
		max_file_size = 1024 * max_file_size_kb
		supported_types_re = re.compile(task.supported_file_types)
		if data:
			contenttype = mimetypes.guess_type(data.name)[0] # don't rely on the browser: data.content_type could be wrong or empty
			if (contenttype is None) or (not (supported_types_re.match(contenttype) or ziptype_re.match(contenttype))):
				raise forms.ValidationError(_('The file of type %s is not supported.' %contenttype))
			if ziptype_re.match(contenttype):
				try:
					zip = zipfile.ZipFile(data)
					if zip.testzip():
						raise forms.ValidationError(_('The zip file seams to be corrupt.'))
					if sum(fileinfo.file_size for fileinfo in zip.infolist()) > 1000000:
						raise forms.ValidationError(_('The zip file is to big.'))	
					for fileinfo in zip.infolist():
						(type, encoding) = mimetypes.guess_type(fileinfo.filename)
						ignorred = SolutionFile.ignorred_file_names_re.search(fileinfo.filename)
						supported = type and supported_types_re.match(type)
						if not ignorred and not supported:
							raise forms.ValidationError(_("The file '%(file)s' of guessed mime type '%(type)s' in this zip file is not supported." %{'file':fileinfo.filename, 'type':type}))
						# check whole zip instead of contained files
						#if fileinfo.file_size > max_file_size:
						#	raise forms.ValidationError(_("The file '%(file)s' is bigger than %(size)iKB which is not suported." %{'file':fileinfo.filename, 'size':max_file_size_kb}))
				except forms.ValidationError:
					raise
				except:
					raise forms.ValidationError(_('Uhoh - something unexpected happened.'))
			if data.size > max_file_size:
				raise forms.ValidationError(_("The file '%(file)s' is bigger than %(size)iKB which is not suported." %{'file':data.name, 'size':max_file_size_kb}))
			return data
开发者ID:t001,项目名称:Praktomat,代码行数:33,代码来源:forms.py

示例15: add_image

 def add_image(self, album_id, imagename, title, comment, reduce_size, size, colors):
     album_url = "/data/feed/api/user/%s/albumid/%s" % (self.email, album_id)
     mime = mimetypes.guess_type(imagename)[0]
     if mime in SUPPORTED_MIMES or mime in CONVERTED_MIMES:
         temp = None
         if reduce_size is True or colors is True or mime in CONVERTED_MIMES:
             image = Image.open(imagename)
             w, h = image.size
             temp = tempfile.mkstemp(suffix=".png", prefix="picapy_tmp", dir="/tmp")[1]
             print(("converting from %s to %s" % (imagename, temp)))
             if reduce_size is True and (w > size or h > size):
                 maximo = size
                 if w > h:
                     h = h * maximo / w
                     w = maximo
                 else:
                     w = w * maximo / h
                     h = maximo
                 image = image.resize([w, h], Image.ANTIALIAS)
             if colors is True:
                 image = image.convert("P", palette=Image.WEB)
             image.save(temp)
             imagename = temp
             mime = mimetypes.guess_type(imagename)[0]
         try:
             photo = self.gd_client.InsertPhotoSimple(album_url, title, comment, imagename, content_type=mime)
         except GooglePhotosExceptio as e:
             self.gd_client = gdata.photos.service.PhotosService()
             self.gd_client.ProgrammaticLogin()
             photo = self.gd_client.InsertPhotoSimple(album_url, title, comment, imagename, content_type=mime)
         if temp is not None and os.path.exists(temp):
             os.remove(temp)
         return photo
开发者ID:atareao,项目名称:Picapy,代码行数:33,代码来源:picasa.py


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