本文整理汇总了Python中mimeparse.best_match函数的典型用法代码示例。如果您正苦于以下问题:Python best_match函数的具体用法?Python best_match怎么用?Python best_match使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了best_match函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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."
示例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
示例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"
}
示例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"
}
示例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 {}
示例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
示例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()
示例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
示例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)
示例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"]
}
示例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
示例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)
示例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
示例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)
示例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)