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

Python mimeparse.best_match函数代码示例

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

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



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

示例1: wrapper

 def wrapper(self, *args, **kwargs):
     
     client_accept = self.request.headers.get('Accept', JSON)
     content_type = self.request.headers.get('Content-Type', FORM)
     
     if '_force_json' in self.request.params:
         client_accept = JSON
     
     input_format = mimeparse.best_match([FORM, JSON, XML], content_type)
     output_format = mimeparse.best_match([JSON, XML], client_accept)
     
     msg, msg_ok = input and input() or None, True
     
     if msg:
         if input_format == JSON:
             try:
                 msg_ok = msg.check(json.loads(self.request.body))
             except ValueError, e:
                 msg_ok = False
                 msg._errors['_major_'] = str(e)
             
         elif input_format == XML:
             msg_ok = msg.check(xmltodict.parse(self.request.body))
         elif input_format == FORM:
             msg_ok = msg.check(self.request.params)
         else:
             msg_ok = False
             msg._errors['_major_'] = "Invalid content type."
开发者ID:mentat,项目名称:restifier,代码行数:28,代码来源:decorators.py


示例2: decide_mimetype

	def decide_mimetype(self, accepts, context_aware = False):
		""" Returns what mimetype the client wants to receive
		    Parses the given Accept header and returns the best one that
		    we know how to output
		    An empty Accept will default to application/rdf+xml
		    An Accept with */* use rdf+xml unless a better match is found
		    An Accept that doesn't match anything will return None
		"""
		mimetype = None
		# If the client didn't request a thing, use default
		if accepts is None or accepts.strip() == '':
			mimetype = self.get_default_mimetype()
			return mimetype

		# pick the mimetype
		if context_aware:
			mimetype = mimeparse.best_match(all_mimetypes + self.all_mimetypes + [WILDCARD], accepts)
		else:
			mimetype = mimeparse.best_match(ctxless_mimetypes + self.ctxless_mimetypes + [WILDCARD], accepts)
		if mimetype == '':
			mimetype = None

		# if browser sent */*
		if mimetype == WILDCARD:
			mimetype = self.get_wildcard_mimetype()

		return mimetype
开发者ID:hufman,项目名称:flask_rdf,代码行数:27,代码来源:format.py


示例3: put_task

def put_task(userid):

    if not verify_user(userid,request.query['token']): return {"RESULT":"YOU ARE NOT AUTHORIZED USER"}

    # Check to make sure JSON is ok
    type = mimeparse.best_match(['application/json'], request.headers.get('Accept'))
    if not type: return abort(406)

    print "Content-Type: %s" % request.headers.get('Content-Type')

    # Check to make sure the data we're getting is JSON
    #if request.headers.get('Content-Type') != 'application/json': return abort(415)

    response.headers.append('Content-Type', type)

    # Read in the data
    data = json.load(request.body)
    name = data.get('name')
    password = data.get('password')
    email = data.get('email')

    print "updating user info(new): userid:%s, name:%s, password:%s, email:%s" % (userid,name,password,email)
    firebase_edit_user(userid,name,password,email)
    # Return the new rating for the entity
    return {
        "Result": "OK"
    }
开发者ID:Yunfeng01,项目名称:SmartRoom,代码行数:27,代码来源:api.py


示例4: update_contact

def update_contact(no):
    # Check to make sure JSON is ok
    type = mimeparse.best_match(['application/json'], request.headers.get('Accept'))
    if not type: return abort(406)

    print "Content-Type: %s" % request.headers.get('Content-Type')

    # Check to make sure the data we're getting is JSON
    #if request.headers.get('Content-Type') != 'application/json': return abort(415)
    response.headers.append('Content-Type', type)

    # Read in the data
    data = json.load(request.body)
    firstname = data.get('first_name')
    lastname = data.get('last_name')
    email = data.get('email')
    phone = data.get('phone')
    notes = data.get('notes')

    print no,firstname,lastname,email,phone,notes
    db_update_contact(no,firstname,lastname,email,phone,notes)

    # Basic sanity checks on the task
    #if iscommand(command): command = command
    #if not iscommand(command): return {"Result": "ERROR: your comamnd doesnot allowed in our api"}   #   abort(400)
    # Return the new rating for the entity
    return {
        "Result": "OK"
    }
开发者ID:chopeace,项目名称:greens9,代码行数:29,代码来源:exer9.py


示例5: select_contact

def select_contact(no):
    # Check to make sure JSON is ok
    type = mimeparse.best_match(['application/json'], request.headers.get('Accept'))
    if not type: return abort(406)

    print "Content-Type: %s" % request.headers.get('Content-Type')

    # Check to make sure the data we're getting is JSON
    #if request.headers.get('Content-Type') != 'application/json': return abort(415)
    response.headers.append('Content-Type', type)
    
    # id, firstname,lastname,email,phone,notes
    conn = sqlite3.connect(db_path)
    c = conn.cursor()
    rows_count = c.execute("SELECT id, firstname,lastname,email,phone,notes FROM contact WHERE id LIKE ?", (str(no)))

    if rows_count > 0:
        rs = c.fetchall()
        conn.close()
        firstRow = rs[0]
        print "firstRow: " , firstRow
        #json_data = json.dumps(cur_data[0]);#first row
        #print "json_data:", json_data
        #return template('{{json}}', json =json_data )
        return {
            "first_name": firstRow[1],
            "last_name": firstRow[2],
            "email": firstRow[3],
            "phone": firstRow[4],
            "notes": firstRow[5]
        }
    else:
        return {}
开发者ID:chopeace,项目名称:greens9,代码行数:33,代码来源:exer9.py


示例6: render

 def render(self, context=None, **kwargs):
     """
     Renders the desired template (determined via the client's accepted mime
     types) with the context. Accepts the same kwargs as render_to_response. 
     """
     desired_template = ''
     content_type = 'text/html'
     
     if self.templates == {}:
         raise RuntimeError('You must register at least one mime type and template with MultiResponse before rendering.')
     
     if 'HTTP_ACCEPT' in self.request.META:
         registered_types = []
         
         for mime, short in self.accept_header_mapping.items():
             if short in self.templates.keys():
                 registered_types.append(mime)
         
         content_type = mimeparse.best_match(registered_types, self.request.META['HTTP_ACCEPT'])
         short_type = self.accept_header_mapping.get(content_type)
         
         if short_type in self.templates.keys():
             desired_template = self.templates.get(short_type)
 
     if not desired_template:
         try:
             desired_template = self.templates.get(self.default_type)
             # Fail miserably.
             content_type = 'text/plain'
         except KeyError:
             raise RuntimeError('The default mime type could not be found in the registered templates.')
 
     response = render_to_response(desired_template, context, **kwargs)
     response['Content-Type'] = "%s; charset=%s" % (content_type, settings.DEFAULT_CHARSET)
     return response
开发者ID:Mondego,项目名称:pyreco,代码行数:35,代码来源:allPythonContent.py


示例7: f1

    def f1(request, **kwargs):
        # construct a http redirect response to html view
        html_view = f.func_name.replace('_rdf', '')
        html_url = urlresolvers.reverse('openoni_%s' % html_view, kwargs=kwargs)
        html_redirect = HttpResponseSeeOther(html_url)

        # determine the clients preferred representation
        available = ['text/html', 'application/rdf+xml']
        accept = request.META.get('HTTP_ACCEPT', 'application/rdf+xml')
        match = best_match(available, accept)

        # figure out what user agent we are talking to
        ua = request.META.get('HTTP_USER_AGENT')

        if request.get_full_path().endswith('.rdf'):
            return f(request, **kwargs)
        elif ua and 'MSIE' in ua:
            return html_redirect
        elif match == 'application/rdf+xml':
            response = f(request, **kwargs)
            response['Vary'] = 'Accept'
            return response
        elif match == 'text/html':
            return html_redirect 
        else:
            return HttpResponseUnsupportedMediaType()
开发者ID:edsu,项目名称:open-oni,代码行数:26,代码来源:decorator.py


示例8: determine_format

def determine_format(request, format, serializer, default_format='application/json'):
    """
    Tries to "smartly" determine which output format is desired.

    First attempts to find a ``format`` override from the request and supplies
    that if found.

    If no request format was demanded, it falls back to ``mimeparse`` and the
    ``Accepts`` header, allowing specification that way.

    If still no format is found, returns the ``default_format`` (which defaults
    to ``application/json`` if not provided).
    """
    # First, check if they forced the format.
    if format in serializer.formats:
        return serializer.get_mime_for_format(format)

    # If callback parameter is present, use JSONP.
    if 'callback' in request.GET:
        return serializer.get_mime_for_format('jsonp')

    # Try to fallback on the Accepts header.
    if request.META.get('HTTP_ACCEPT', '*/*') != '*/*':
        formats = list(serializer.supported_formats) or []
        # Reverse the list, because mimeparse is weird like that. See also
        # https://github.com/toastdriven/django-tastypie/issues#issue/12 for
        # more information.
        formats.reverse()
        best_format = mimeparse.best_match(formats, request.META['HTTP_ACCEPT'])

        if best_format:
            return best_format

    # No valid 'Accept' header/formats. Sane default.
    return default_format
开发者ID:georgemarshall,项目名称:django-apiserver,代码行数:35,代码来源:mime.py


示例9: ConfigureRequest

  def ConfigureRequest(self, upload_config, http_request, url_builder):
    """Configure the request and url for this upload."""
    # Validate total_size vs. max_size
    if (self.total_size and upload_config.max_size and
        self.total_size > upload_config.max_size):
      raise exceptions.InvalidUserInputError(
          'Upload too big: %s larger than max size %s' % (
              self.total_size, upload_config.max_size))
    # Validate mime type
    if not mimeparse.best_match(upload_config.accept, self.mime_type):
      raise exceptions.InvalidUserInputError(
          'MIME type %s does not match any accepted MIME ranges %s' % (
              self.mime_type, upload_config.accept))

    self.__SetDefaultUploadStrategy(upload_config, http_request)
    if self.strategy == _SIMPLE_UPLOAD:
      url_builder.relative_path = upload_config.simple_path
      if http_request.body:
        url_builder.query_params['uploadType'] = 'multipart'
        self.__ConfigureMultipartRequest(http_request)
      else:
        url_builder.query_params['uploadType'] = 'media'
        self.__ConfigureMediaRequest(http_request)
    else:
      url_builder.relative_path = upload_config.resumable_path
      url_builder.query_params['uploadType'] = 'resumable'
      self.__ConfigureResumableRequest(http_request)
开发者ID:Technology-Hatchery,项目名称:google-cloud-sdk,代码行数:27,代码来源:transfer.py


示例10: put_rating

def put_rating(entity):
	# Check to make sure JSON is ok
	mimetype = mimeparse.best_match(['application/json'], request.headers.get('Accept'))
	if not mimetype: return abort(406)

	# Check to make sure the data we're getting is JSON
	if request.headers.get('Content-Type') != 'application/json': return abort(415)

	response.headers.append('Content-Type', mimetype)

	# Parse the request
	data = json.load(request.body)
	setrating = data.get('rating')
	setclock = VectorClock.fromDict(data.get('clock'))
	
	key = '/rating/'+entity
	#key = '/rating-and-clock/'+entity

	#sync_with_neighbour_queue(key)
	merge_with_db(setrating, setclock, key)
	sync_with_neighbour_queue(key)
	
	# lets grab the results of our work!	
	result = get_final_rating_result(key) 

	#final_rating_key = '/rating/'+entity
	#client.hset(final_rating_key, 'rating', result["rating"])
	
	# Return rating
	return {
		"rating": result["rating"]
	}
开发者ID:kkc47,项目名称:Distributed-System--Rating-System,代码行数:32,代码来源:serverDB.py


示例11: determine_format

def determine_format(request, serializer, default_format='application/json'):
    """
    Tries to "smartly" determine which output format is desired.
    
    First attempts to find a ``format`` override from the request and supplies
    that if found.
    
    If no request format was demanded, it falls back to ``mimeparse`` and the
    ``Accepts`` header, allowing specification that way.
    
    If still no format is found, returns the ``default_format`` (which defaults
    to ``application/json`` if not provided).
    """
    # First, check if they forced the format.
    if request.GET.get('format'):
        if request.GET['format'] in serializer.formats:
            return serializer.get_mime_for_format(request.GET['format'])
    
    # If callback parameter is present, use JSONP.
    if request.GET.has_key('callback'):
        return serializer.get_mime_for_format('jsonp')
    
    # Try to fallback on the Accepts header.
    if request.META.get('HTTP_ACCEPT', '*/*') != '*/*':
        best_format = mimeparse.best_match(serializer.supported_formats, request.META['HTTP_ACCEPT'])
        
        if best_format:
            return best_format
    
    # No valid 'Accept' header/formats. Sane default.
    return default_format
开发者ID:codysoyland,项目名称:django-tastypie,代码行数:31,代码来源:mime.py


示例12: init_response

 def init_response(self, request):
     accept = request.META.get('HTTP_ACCEPT', None)
     if not accept:
         raise Http406
     
     try:
         self.mime = mimeparse.best_match([x[0] for x in self.serializers], accept)
         if not self.mime:
             raise ValueError
     except ValueError:
         raise Http406
     
     # Reading data
     if request.method in ('POST', 'PUT'):
         content_type = request.META.get('CONTENT_TYPE', '').split(';',1)[0]
         
         deserializers = dict(self.deserializers)
         deserializer = deserializers.get(content_type)
         # We may have a default deserializer
         if not deserializer:
             deserializer = deserializers.get('*/*')
         
         if not deserializer:
             raise Http406
         try:
             request.data = deserializer(request)
         except BaseException, e:
             raise HttpException(str(e), 400)
开发者ID:pombredanne,项目名称:django-restlayer,代码行数:28,代码来源:base.py


示例13: wrapper

 def wrapper(request, *args, **kwargs):
     context_dictionary = view_func(request, *args, **kwargs)
     context_instance = self.request_context and RequestContext(request) or Context()
     
     if self.template_mapping:
         content_type = mimeparse.best_match(self.template_mapping.keys(),\
                             request.META['HTTP_ACCEPT'])
     else:
         content_type = settings.DEFAULT_MIMETYPE
     
     if self.template_mapping.has_key(content_type):
         template_name = self.template_mapping.get(content_type)
     elif kwargs.has_key(settings.FORMAT_STRING) and \
          kwargs.get(settings.FORMAT_STRING) in self.allowed_format:
         format = kwargs.get(settings.FORMAT_STRING)
         template_name = '%s.%s' % (view_func.__name__, format)
         content_type = settings.ALLOWED_FORMAT.get(format)
     else:
         raise Http404
     
     response = render_to_response(template_name,
                                   context_dictionary,
                                   context_instance=context_instance)
     response['Content-Type'] = "%s; charset=%s" % (content_type, settings.DEFAULT_CHARSET)
     return response
开发者ID:thoas,项目名称:i386,代码行数:25,代码来源:views.py


示例14: contentNegotiation

def contentNegotiation(req, extension, queryset, single=True):
    acceptedExtensions = {'.json': 'json',
                          '.geojson': 'geojson',
                          '.kml': 'kml',
                          '.csv': 'csv',
                          '.js': 'js'}
    acceptedTypes = {'application/json': 'json',
                     'application/geojson': 'geojson',
                     'application/vnd.google-earth.kml+xml': 'kml',
                     'text/csv': 'csv',
                     'text/javascript': 'js',
                     'application/javascript': 'js'}
    accept = req.META.get('HTTP_ACCEPT', 'text/csv').lower()

    if extension != None and extension in acceptedExtensions.keys():
        format = acceptedExtensions[extension]
    else:
        bestType = mimeparse.best_match(acceptedTypes.keys(), accept)
        if bestType in acceptedTypes.keys():
            format = acceptedTypes[bestType]
        else:
            return HttpResponse('Not Acceptable', status=406)

    if format == 'json':
        return HttpSimpleJsonResponse(queryset, single)
    elif format == 'geojson':
        return HttpGeoJsonResponse(queryset, single)
    elif format == 'kml':
        return HttpKmlResponse(queryset)
    elif format == 'csv':
        return HttpCsvResponse(queryset)
    elif format == 'js':
        return HttpJsResponse(queryset, single)
开发者ID:asonnenschein,项目名称:quakedb,代码行数:33,代码来源:views.py


示例15: render_to_response

    def render_to_response(self, request, data=None, status=200):
        mimetype = mimeparse.best_match(self.supported_mimetypes.keys(), request.META['HTTP_ACCEPT'])
        mimetype = mimetypes.guess_type(request.path_info.rstrip('/'))[0] or mimetype
        content_type = '%s; charset=%s' % (mimetype, settings.DEFAULT_CHARSET)

        templ_or_func = self.supported_mimetypes.get(mimetype)

        # If a template or function isn't found, return a 415 (unsupportted media type) response
        if not templ_or_func:
            return HttpResponse(status=415)

        if isinstance(templ_or_func, str):
            def serialize(data):
                data = data or {}
                response = render_to_response(templ_or_func, data)
                response['Content-Type'] = content_type
                response.status_code = status
                return response
        else:
            def serialize(data):
                if data:
                    response = HttpResponse(templ_or_func(data), content_type=content_type, status=status)
                else:
                    response = HttpResponse(content_type=content_type, status=status)
                return response

        return serialize(data)
开发者ID:MechanisM,项目名称:django-simple-rest,代码行数:27,代码来源:response.py


示例16: determine_emitter

 def determine_emitter(self, request, *args, **kwargs):
     """
     Function for determening which emitter to use
     for output. It lives here so you can easily subclass
     `Resource` in order to change how emission is detected.
     """
     try:
         return kwargs['emitter_format']
     except KeyError:
         pass
     if 'format' in request.GET:
         return request.GET.get('format')
     if mimeparse and 'HTTP_ACCEPT' in request.META:
         supported_mime_types = set()
         emitter_map = {}
         for name, (klass, content_type) in Emitter.EMITTERS.items():
             content_type_without_encoding = content_type.split(';')[0]
             supported_mime_types.add(content_type_without_encoding)
             emitter_map[content_type_without_encoding] = emitter_map.get(content_type_without_encoding, name)
         supported_mime_types = list(supported_mime_types)
         supported_mime_types.append(self.preffered_content_type)
         preferred_content_type = mimeparse.best_match(
             supported_mime_types,
             request.META['HTTP_ACCEPT'])
         return emitter_map.get(preferred_content_type, None)
开发者ID:bobisjan,项目名称:django-piston,代码行数:25,代码来源:resource.py


示例17: _test_best_match

 def _test_best_match(self, args, expected, description):
     if expected is None:
         self.assertRaises(mimeparse.MimeTypeParseException, mimeparse.best_match, args[0], args[1])
     else:
         result = mimeparse.best_match(args[0], args[1])
         message = "Expected: '%s' but got %s. Description for this test: %s" % (expected, result, description)
         self.assertEqual(expected, result, message)
开发者ID:adamchainz,项目名称:python-mimeparse,代码行数:7,代码来源:mimeparse_test.py


示例18: best_match

    def best_match(self, accept, default=None):
        """
        get the media type provided by this simplate that best matches
        the supplied Accept: header, or the default type (that of the
        first template page) if no accept header is provided (is None),
        or raise SimplateException if no matches are available
        to a valid Accept: header.

        This is what the simplate will call internally to determine
        which template to use.
        """
        _, media_type = self.pages[2]  # default to first content page
        if accept is None:
            # No accept header provided, use the default
            return media_type
        try:
            media_type = mimeparse.best_match(self.available_types, accept)
        except:
            # exception means don't override the defaults
            log( "Problem with mimeparse.best_match(%r, %r): %r "
                % (self.available_types, accept, sys.exc_info())
                )
        else:
            if media_type == '':    # breakdown in negotiations
                raise SimplateException(self.available_types)
        return media_type
开发者ID:jaraco,项目名称:aspen,代码行数:26,代码来源:__init__.py


示例19: get_feed_type

	def get_feed_type(self, request, feed_type=None):
		"""
		If ``feed_type`` is not ``None``, returns the corresponding class from the registry or raises :exc:`.HttpNotAcceptable`.
		
		Otherwise, intelligently chooses a feed type for a given request. Tries to return :attr:`feed_type`, but if the Accept header does not include that mimetype, tries to return the best match from the feed types that are offered by the :class:`FeedView`. If none of the offered feed types are accepted by the :class:`HttpRequest`, raises :exc:`.HttpNotAcceptable`.
		
		If `mimeparse <http://code.google.com/p/mimeparse/>`_ is installed, it will be used to select the best matching accepted format; otherwise, the first available format that is accepted will be selected.
		
		"""
		if feed_type is not None:
			feed_type = registry[feed_type]
			loose = False
		else:
			feed_type = registry.get(self.feed_type, DEFAULT_FEED)
			loose = True
		mt = feed_type.mime_type
		accept = request.META.get('HTTP_ACCEPT')
		if accept and mt not in accept and "*/*" not in accept and "%s/*" % mt.split("/")[0] not in accept:
			# Wups! They aren't accepting the chosen format.
			feed_type = None
			if loose:
				# Is there another format we can use?
				accepted_mts = dict([(obj.mime_type, obj) for obj in registry.values()])
				if mimeparse:
					mt = mimeparse.best_match(accepted_mts.keys(), accept)
					if mt:
						feed_type = accepted_mts[mt]
				else:
					for mt in accepted_mts:
						if mt in accept or "%s/*" % mt.split("/")[0] in accept:
							feed_type = accepted_mts[mt]
							break
			if not feed_type:
				raise HttpNotAcceptable
		return feed_type
开发者ID:MechanisM,项目名称:philo,代码行数:35,代码来源:models.py


示例20: team_index

def team_index(request, format=None):
            logging.info("Format: %s" % format)

            if format == None:
                best_match = mimeparse.best_match(['application/rdf+xml', 'application/rdf+n3', 'text/html'], request.META['HTTP_ACCEPT'])
                if best_match == 'application/rdf+xml':
                    format = 'rdf+xml'
                elif best_match == 'application/rdf+nt':
                    format = 'rdf+nt'
                else:
                    format = 'html'

            team_list = College.objects.filter(updated=True).order_by('name')

            if ( format != 'html'):
                store = Graph()

                store.bind("cfb", "http://www.cfbreference.com/cfb/0.1/")

                CFB = Namespace("http://www.cfbreference.com/cfb/0.1/")

                for current_team in team_list:
                    team = BNode()

                    store.add((team, RDF.type, CFB["Team"]))
                    store.add((team, CFB["name"], Literal(current_team.name)))
                    store.add((team, CFB["link"], Literal(current_team.get_absolute_url())))
                if ( format == 'rdf+xml'):
                    return HttpResponse(store.serialize(format="pretty-xml"), mimetype='application/rdf+xml')
                if ( format == 'rdf+nt'):
                    return HttpResponse(store.serialize(format="nt"), mimetype='application/rdf+nt')

            return render_to_response('college/teams.html', {'team_list': team_list})
开发者ID:jeremyjbowers,项目名称:cfbreference_com,代码行数:33,代码来源:views.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python mimeparse.parse_mime_type函数代码示例发布时间:2022-05-27
下一篇:
Python miller.grade函数代码示例发布时间: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