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."
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
def media_type(resource, request): if ("Accept" in request.headers and request.headers["Accept"] not in resource.acceptable_media_types): return webob.Response(status=406) else: acceptable = ("Accept" in request.headers and request.headers["Accept"] or "*/*") mimeparse.best_match(resource.acceptable_media_types, acceptable)
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)
def general_error_guard(e): name = str(uuid4()) log.exception(name) template = '出错了. 错误编号 %s . 你可以提交该编号给 %s , 协助改进torabot.' def format_json(): return jsonify( dict(message=dict( text=template % (name, current_app.config.get('TORABOT_REPORT_EMAIL', '')), html=template % (name, "<a href='mailto:{0}' target=_blank>{0}</a>".format( current_app.config.get('TORABOT_REPORT_EMAIL', '')))))) def format_html(): return render_template( 'message.html', ok=False, message=template % (name, current_app.config.get('TORABOT_REPORT_EMAIL', '')), ) formats = { 'application/json': format_json, 'text/html': format_html, } return formats[mimeparse.best_match(formats, request.headers['accept'])](), 400
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
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()
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 {}
def serialize_response(self, response, status=200): """ Serializes the response into an appropriate format for the wire such as JSON. ``HttpResponse`` instances are returned directly. """ if isinstance(response, HttpResponse): return response formats = [ ('application/json', { 'handler': lambda response, output_format, config: ( HttpResponse(json.dumps(response, cls=DjangoJSONEncoder), mimetype='application/json', status=status)), }), #('text/html', { #'handler': self.serialize_response_html, #}), ] # Thanks! # https://github.com/toastdriven/django-tastypie/blob/master/tastypie/utils/mime.py try: output_format = mimeparse.best_match( reversed([format for format, config in formats]), self.request.META.get('HTTP_ACCEPT')) except IndexError: output_format = 'application/json' config = dict(formats)[output_format] response = config['handler'](response, output_format, config) patch_vary_headers(response, ('Accept',)) return response
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
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" }
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)
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)
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)
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"}
def lookup_handler(self, media_type, default_media_type=None): """Lookup media handler by media type. Args: media_type (str): A media type of the registered media handler default_media_type (str): The default media type to use when `media_type` is not specified Returns: BaseMediaHandler: A media handler. Raises: falcon.HTTPUnsupportedMediaType: If `content_type` is not supported """ if media_type == '*/*' or not media_type: media_type = default_media_type or self.media_type handler = self.handlers.get(media_type, None) if handler is None: try: resolved = mimeparse.best_match(self.handlers, media_type) assert not resolved handler = self.handlers[resolved] except (AssertionError, KeyError, ValueError): allowed = ', '.join("'{}'".format(media_type) for media_type in self.allowed_media_types) raise falcon.HTTPUnsupportedMediaType( description="'{}' is an unsupported media type, supported " "media types: {}".format(media_type, allowed)) else: self.handlers[media_type] = handler return handler
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"] }
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
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)
def dispatch(self, method, mime_type): """Pass in the method and the media-range and the best matching function will be called. For example, if BaseHttpDispatch is constructed with a mime type map that maps 'text/xml' to 'xml', then if dispatch is called with 'POST' and 'text/xml' will first look for 'POST_xml' and then if that fails it will try to call 'POST'. Each function so defined must return a tuple (headers, body) where 'headers' is a dictionary of headers for the response and 'body' is any object that simulates a file. """ returnValue = ({}, StringIO("")) if mime_type and self.mime_types_supported: match = mimeparse.best_match(self.mime_types_supported.keys(), mime_type) mime_type_short_name = self.mime_types_supported.get(match , '') else: mime_type_short_name = "" fun_name = method + "_" + mime_type_short_name if fun_name in dir(self) and callable(getattr(self, fun_name)): returnValue = self._call_fn(fun_name, method, mime_type) elif method in dir(self) and callable(getattr(self, method)): returnValue = self._call_fn(method, method, mime_type) else: returnValue = self.nomatch(method, mime_type) return returnValue
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']) # 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
def post_item(): """ Just a demonstration of POST. It particularly shows how to handle CORS issues. """ print "Entered post_item" # 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) response.headers.append("Access-Control-Allow-Origin", "*") # Parse the request data = json.load(request.body) print "Received", data print "Ready to return from POST" return {"answer": "Done"}
def responseexception_factory(request, response_code, title, message, response_class=HttpResponse): rest_mime_types = list(get_supported_mime_types()) ui_mime_types = ['text/html', 'application/xhtml+xml'] best_match = mimeparse.best_match(rest_mime_types + ui_mime_types, request.META.get('HTTP_ACCEPT', 'text/html')) resp_message = message if best_match in ui_mime_types: if isinstance(resp_message, (list, tuple)): resp_message = ', '.join(resp_message) context = {'response_code': response_code, 'title': title, 'message': resp_message} content = render_to_string(('%s.html' % response_code, 'error.html'), context, context_instance=RequestContext(request)) ct = None else: if resp_message: if isinstance(resp_message, (list, tuple)): resp_message = [force_text(val) for val in resp_message] else: resp_message = force_text(resp_message) else: resp_message = force_text(title) set_rest_context_to_request(request, BaseResource.DEFAULT_REST_CONTEXT_MAPPING) converter, ct = get_converter_from_request(request) content = converter().encode(request, {'error': resp_message}, None, message) return response_class(content, status=response_code, content_type=ct)
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) command = data.get('command') devicename = data.get('devicename') executedate = data.get('executedate') print "requested command:%s, devicename:%s, executedate:%s" % (command,devicename,executedate) # 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) # Send a message to a robot to begin processing actual switching on/off notify_robot(userid,command,devicename,executedate) # Return the new rating for the entity return { "Result": "OK" }
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" }
def find_formatter_type(accept_header=None, **kw): if accept_header is None: accept_header = "application/xml" accept_header = mimeparse.best_match(CONTENT_TYPE_CONVERTERS.keys(), accept_header) type_ = CONTENT_TYPE_CONVERTERS.get(accept_header, NO_CONV)[2] return type_
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})
def get_response_type(self): response_type = self.view.patched_meta.get('HTTP_ACCEPT', '') effective_type = response_type.split(self.recognized_media_types[0], 1)[-1] return mimeparse.best_match( self.site.media_types.keys(), effective_type )
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
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
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)
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
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)
def render(self, result, mimetype, errors=None): """ Render a model result into `mimetype` format. """ available_mimetypes = [x for x in self.render_map.keys() if '/' in x] render_func = None if '/' not in mimetype: # naked superformat (does not correspond to a mimetype) render_func = self.reject_map.get(mimetype, None) if not render_func: raise NoViewMethod("Unknown Superformat: %s" % mimetype) if not render_func and available_mimetypes: target_mimetype = mimeparse.best_match(available_mimetypes, mimetype) render_func = self.render_map.get(target_mimetype, None) if not render_func: raise NoViewMethod("%s not supported for this program" % mimetype) principle_mimetype = render_func.mimetypes[0] if GiottoControl in render_func.__class__.mro(): # redirection defined as view (not wrapped in lambda) return {'body': render_func, 'persist': render_func.persist} if callable(self.persist): # persist (cookie data) can be either an object, or a callable) persist = self.persist(result) else: persist = self.persist # render functins can take either one or two arguments, both are # supported by the API arg_names = inspect.getargspec(render_func).args num_args = len(set(arg_names) - set(['self', 'cls'])) if num_args == 2: data = render_func(result, errors or Mock()) else: # if the renderer only has one argument, don't pass in the 2nd arg. data = render_func(result) if GiottoControl in data.__class__.mro(): # render function returned a control object return {'body': data, 'persist': persist} if not hasattr(data, 'items'): # view returned string data = {'body': data, 'mimetype': principle_mimetype} else: # result is a dict in for form {body: XX, mimetype: xx} if not 'mimetype' in data and target_mimetype == '*/*': data['mimetype'] = '' if not 'mimetype' in data: data['mimetype'] = target_mimetype data['persist'] = persist return data
def index(): use = mimeparse.best_match(['application/json', 'text/html'], bottle.request.header.get('accept')) if use == 'application/json': return {'message': '', 'accept': bottle.request.header.get('accept'), 'use': use} else: return bottle.static_file('index.html', root=app.config['media_root'])
def request_prefers_json_over_html(): """True if request Accept header indicates preference for json over html.""" try: best_mimetype = mimeparse.best_match(["application/json", "text/html"], request.headers["Accept"]) return best_mimetype == "application/json" except: # E.g. best_matches raises if mimetype does not even contain a '/'. return False
def getFormat(self, contentType): if contentType == None: return [ "application/rdf+xml;",self.contentTypes[None]] print contentType type = mimeparse.best_match([x for x in self.contentTypes.keys() if x != None], contentType) if type != None: return [type,self.contentTypes[type]] else: return [ "application/rdf+xml",serializeXML]
def getFormat(self, contentType): if contentType == None: return ["application/rdf+xml;", self.contentTypes[None]] print contentType type = mimeparse.best_match( [x for x in self.contentTypes.keys() if x != None], contentType) if type != None: return [type, self.contentTypes[type]] else: return ["application/rdf+xml", serializeXML]
def get_preferred_mimetype(acceptable, default): """ Gets the preferred MIME type to use for rendering the response based on what the client will accept. """ if 'HTTP_ACCEPT' not in web.ctx.env: return default return mimeparse.best_match(acceptable, web.ctx.env['HTTP_ACCEPT'])
async def wrapper(request): header = request.headers.get('ACCEPT', '*/*') best_match = mimeparse.best_match(content_types, header) if not best_match or best_match not in content_types: raise web.HTTPNotAcceptable return await func(request)
def check_client_accpets_application_json(): accept_header = request.headers.get('accept', '*/*') best_response_mimetype = mimeparse.best_match(('application/json', ), accept_header) if best_response_mimetype == '': msg = "The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request" details = {'supported_mime_types': ['application/json']} return build_response({'error': msg, 'details': details}, 406)
def get_handlers(self): mimetype_handlers = self.get_mime_to_handlers() mime_match = mimeparse.best_match(mimetype_handlers.keys(), self.mimetype) str_or_tup = mimetype_handlers[mime_match] while isinstance(str_or_tup, str): str_or_tup = mimetype_handlers[str_or_tup] return str_or_tup
def get_content_type_based_on(self, header_key): mimetypes = self.get_mimetypes_priority() default_encoding = mimetypes[-1] content_types_by_client = self.request.headers.get( header_key, default_encoding) if content_types_by_client == SIMPLE_POST_MIMETYPE: content_types_by_client = default_encoding content_type = mimeparse.best_match(mimetypes, content_types_by_client) return content_type
def _get_best_matched(self, key: str) -> ty.Optional[t.AbstractConvertible[T]]: best = self.allowed.get(key) if best is None: match = mimeparse.best_match(self.allowed.keys(), key) if match: best = self.allowed[match] return best
def request_prefers_json_over_html(): """True if request Accept header indicates preference for json over html.""" try: best_mimetype = mimeparse.best_match(['application/json', 'text/html'], request.headers['Accept']) return best_mimetype == 'application/json' except: # E.g. best_matches raises if mimetype does not even contain a '/'. return False
def content_type_supported(self, request, response, *args, **kwargs): content_type = request.META['CONTENT_TYPE'] mimetypes = list(self.supported_content_types) mimetypes.reverse() match = mimeparse.best_match(mimetypes, content_type) if match: request._content_type = match return True return False
def get_response_type(request): supported = get_supported() header = request.META['HTTP_ACCEPT'] match = mimeparse.best_match(supported, header) if match: return match else: raise NotAcceptable()
def render(self, state): """Render the resource with the given state as context, return Output. Before rendering we need to determine what type of content we're going to send back, by trying to find a match between the media types the client wants and the ones provided by the resource. The two sources for what the client wants are the extension in the request URL, and the Accept header. If the former fails to match we raise NotFound (404), if the latter fails we raise NegotiationFailure (406). Note that we don't always respect the `Accept` header (the spec says we can ignore it: <https://tools.ietf.org/html/rfc7231#section-5.3.2>). """ available = self.available_types dispatch_extension = state['dispatch_result'].extension if dispatch_extension: # There's an extension in the URI path, guess the media type from it dispatch_accept = mimetypes.guess_type('a.' + dispatch_extension, strict=False)[0] if dispatch_accept is None: # The extension is unknown, raise NotFound raise NotFound() accept = dispatch_accept # Accept `media/type` for `media/x-type` i = accept.find('/x-') if i > 0: accept += ',' + accept[:i + 1] + accept[i + 3:] # Accept custom JSON media type if accept == 'application/json': accept += ',' + self.request_processor.media_type_json elif len(available) == 1: # If there's only one available type and no extension in the path, # then we ignore the Accept header return self.render_for_type(available[0], state) else: dispatch_accept = None accept = state.get('accept_header') if accept: try: best_match = mimeparse.best_match(available, accept) except ValueError: # Unparseable accept header best_match = None if best_match: return self.render_for_type(best_match, state) elif best_match == '': if dispatch_accept is not None: # e.g. client requested `/foo.json` but `/foo.spt` has no JSON page raise NotFound() raise NegotiationFailure(accept, available) # Fall back to the first available type return self.render_for_type(available[0], state)
def guess_content_type(self): """ Guesses the client's ``Accept`` header using :mod:`mimeparse` against the supported :attr:`.supported_types`. :return: best match (str) """ return mimeparse.best_match(self.supported_types, self.request.headers.get("accept", ""))
def _negotiate_content_type(self): if not hasattr(self, '_negotiated_content_type'): accept = self.request.headers.get('Accept') self._negotiated_content_type = mimeparse.best_match( self._negotiable_server_content_types, accept) if not self._negotiated_content_type: self.set_status(406) if not self._finished: self.finish() return self._negotiated_content_type
def getFormat(contentType): if contentType == None: return ["application/rdf+xml", contentTypes[None]] type = mimeparse.best_match(["application/rdf+xml"] + [x for x in contentTypes.keys() if x != None], contentType) if type == '' or type == None: return ["application/rdf+xml", DefaultSerializer('xml')] else: return [type, contentTypes[type]]
def find_formatter(format=None, accept_header=None, **kw): if format is not None: return FORMATTERS.get(format, (format_xml, 'text/xml')) # Parse accept header until acceptable is found if accept_header is None: accept_header = "application/xml" accept_header = mimeparse.best_match(CONTENT_TYPE_CONVERTERS.keys(), accept_header) converter = CONTENT_TYPE_CONVERTERS.get(accept_header, NO_CONV)[0] return (converter, accept_header)
def _filter_dispatchers_on_match(dispatchers, match, value): # Build an ordered list of the supported types. supported = [] for d in dispatchers: supported.extend(d[1][match]) # Find the best match # XXX mimeparse picks *last* matching item so we reverse. supported.reverse() best_match = mimeparse.best_match(supported, value) # Return the matching dispatchers return [d for d in dispatchers if best_match in d[1][match]]
def determine_return_type(request_meta): try: preferred_types = ['application/json', 'text/html'] if "HTTP_ACCEPT" in request_meta: return best_match(preferred_types, request_meta['HTTP_ACCEPT']) return "application/json" except Exception: # pylint: disable=broad-except # This is a bit of a hack - as there is no specific exception that `best_match` function raises in case of # invalid/broken accept header, we just catch every possible exception that comes from it and treat such # a situation as a broken header return ""
async def negotiate(self, request): request.headers.getall('Accept', "*/*") mime_type = mimeparse.best_match( ['application/json', 'text/event-stream'], ",".join(request.headers.getall('Accept', "*/*"))) if mime_type == 'text/event-stream': return await self.event_stream(request) elif mime_type == 'application/json': return await self.json(request) else: raise NotImplementedError(mime_type)
def get_request_type(self): """ Returns the active request type to be used :rtype: string """ val = self.META.get('CONTENT_TYPE', self.META.get('HTTP_ACCEPT', '')) media_types = self.media_types.keys() if not media_types: return val return mimeparse.best_match(media_types, val) or val