def request_wants_json():
"""Based on `Armin's snippet <http://flask.pocoo.org/snippets/45/>`.
"""
best = request.accept_mimetypes.best_match([
'application/json', 'text/html',
])
if best != 'application/json':
return False
json_score = request.accept_mimetypes['application/json']
html_score = request.accept_mimetypes['text/html']
return best == 'application/json' and json_score > html_score
python类accept_mimetypes()的实例源码
def request_wants_json():
best = request.accept_mimetypes \
.best_match(["application/json", "text/html"])
return best == "application/json" and \
request.accept_mimetypes[best] >= \
request.accept_mimetypes["text/html"]
def request_wants_json():
"""
Returns true it the request header has 'application/json'.
This is used to determine whether to return html or json content from
the same endpoint
"""
best = request.accept_mimetypes \
.best_match(['application/json', 'text/html'])
return best == 'application/json' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['text/html']
# some simple helpers. This probably doesn't belong in drift
def request_wants_json():
for mime in request.accept_mimetypes:
if 'json' in mime[0]:
return mime[0]
return False
def before_auth_request():
if 'application/json' not in request.accept_mimetypes:
return errors.not_acceptable()
def before_api_request():
if 'application/json' not in request.accept_mimetypes:
return errors.not_acceptable()
def before_api_request():
if 'application/json' not in request.accept_mimetypes:
return errors.not_acceptable()
def __is_json_request(self):
best = request.accept_mimetypes.best_match(['application/json', 'text/html'])
return best == 'application/json' and request.accept_mimetypes[best] > request.accept_mimetypes['text/html']
def request_wants_html(self):
best = request.accept_mimetypes \
.best_match(['application/json', 'text/html'])
return best == 'text/html' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['application/json']
def val_with_content_type(value, template):
"""Return either json or text/html with value dict."""
mimes = request.accept_mimetypes
json_score = mimes['application/json'] if 'application/json' in mimes else 0
text_html_score = mimes['text/html'] if 'text/html' in mimes else 0
if json_score > text_html_score:
return jsonify(value)
else:
return render_template(template, **value)
def spec():
"""Return the specification of the API."""
swag = get_spec(app)
best = request.accept_mimetypes.best_match(["text/yaml", "application/x-yaml"])
if (best in (
"text/yaml",
"application/x-yaml",
) and request.accept_mimetypes[best] > request.accept_mimetypes["application/json"]):
return yamlfy(swag)
else:
return jsonify(swag)
def request_wants_json():
best = request.accept_mimetypes.best_match(['text/html', 'application/json'])
return best == 'application/json' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['text/html']
def request_wants_json():
"""Checks whether a JSON response is expected base on the Accept-Header.
Flask Snippet: http://flask.pocoo.org/snippets/45/
Returns:
True if JSON is expected, False otherwise.
"""
best = request.accept_mimetypes.best_match(
['application/json', 'text/html'])
return (best == 'application/json' and
request.accept_mimetypes[best] >
request.accept_mimetypes['text/html'])
def make_response(self, data, *args, **kwargs):
"""Looks up the representation transformer for the requested media
type, invoking the transformer to create a response object. This
defaults to default_mediatype if no transformer is found for the
requested mediatype. If default_mediatype is None, a 406 Not
Acceptable response will be sent as per RFC 2616 section 14.1
:param data: Python object containing response data to be transformed
"""
default_mediatype = kwargs.pop('fallback_mediatype', None) or self.default_mediatype
mediatype = request.accept_mimetypes.best_match(
self.representations,
default=default_mediatype,
)
if mediatype is None:
raise NotAcceptable()
if mediatype in self.representations:
resp = self.representations[mediatype](data, *args, **kwargs)
resp.headers['Content-Type'] = mediatype
return resp
elif mediatype == 'text/plain':
resp = original_flask_make_response(str(data), *args, **kwargs)
resp.headers['Content-Type'] = 'text/plain'
return resp
else:
raise InternalServerError()
def mediatypes(self):
"""Returns a list of requested mediatypes sent in the Accept header"""
return [h for h, q in sorted(request.accept_mimetypes,
key=operator.itemgetter(1), reverse=True)]
def dispatch_request(self, *args, **kwargs):
# Taken from flask
#noinspection PyUnresolvedReferences
meth = getattr(self, request.method.lower(), None)
if meth is None and request.method == 'HEAD':
meth = getattr(self, 'get', None)
assert meth is not None, 'Unimplemented method %r' % request.method
for decorator in self.method_decorators:
meth = decorator(meth)
resp = meth(*args, **kwargs)
if isinstance(resp, ResponseBase): # There may be a better way to test
return resp
representations = self.representations or OrderedDict()
#noinspection PyUnresolvedReferences
mediatype = request.accept_mimetypes.best_match(representations, default=None)
if mediatype in representations:
data, code, headers = unpack(resp)
resp = representations[mediatype](data, code, headers)
resp.headers['Content-Type'] = mediatype
return resp
return resp
def request_wants_json():
best = request.accept_mimetypes \
.best_match(['application/json', 'text/html'])
return best == 'application/json' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['text/html']
def make_response(self, data, *args, **kwargs):
"""Looks up the representation transformer for the requested media
type, invoking the transformer to create a response object. This
defaults to default_mediatype if no transformer is found for the
requested mediatype. If default_mediatype is None, a 406 Not
Acceptable response will be sent as per RFC 2616 section 14.1
:param data: Python object containing response data to be transformed
"""
default_mediatype = kwargs.pop('fallback_mediatype', None) or self.default_mediatype
mediatype = request.accept_mimetypes.best_match(
self.representations,
default=default_mediatype,
)
if mediatype is None:
raise NotAcceptable()
if mediatype in self.representations:
resp = self.representations[mediatype](data, *args, **kwargs)
resp.headers['Content-Type'] = mediatype
return resp
elif mediatype == 'text/plain':
resp = original_flask_make_response(str(data), *args, **kwargs)
resp.headers['Content-Type'] = 'text/plain'
return resp
else:
raise InternalServerError()
def mediatypes(self):
"""Returns a list of requested mediatypes sent in the Accept header"""
return [h for h, q in sorted(request.accept_mimetypes,
key=operator.itemgetter(1), reverse=True)]
def dispatch_request(self, *args, **kwargs):
# Taken from flask
#noinspection PyUnresolvedReferences
meth = getattr(self, request.method.lower(), None)
if meth is None and request.method == 'HEAD':
meth = getattr(self, 'get', None)
assert meth is not None, 'Unimplemented method %r' % request.method
for decorator in self.method_decorators:
meth = decorator(meth)
resp = meth(*args, **kwargs)
if isinstance(resp, ResponseBase): # There may be a better way to test
return resp
representations = self.representations or OrderedDict()
#noinspection PyUnresolvedReferences
mediatype = request.accept_mimetypes.best_match(representations, default=None)
if mediatype in representations:
data, code, headers = unpack(resp)
resp = representations[mediatype](data, code, headers)
resp.headers['Content-Type'] = mediatype
return resp
return resp
def make_response(self, data, *args, **kwargs):
"""Looks up the representation transformer for the requested media
type, invoking the transformer to create a response object. This
defaults to default_mediatype if no transformer is found for the
requested mediatype. If default_mediatype is None, a 406 Not
Acceptable response will be sent as per RFC 2616 section 14.1
:param data: Python object containing response data to be transformed
"""
default_mediatype = kwargs.pop('fallback_mediatype', None) or self.default_mediatype
mediatype = request.accept_mimetypes.best_match(
self.representations,
default=default_mediatype,
)
if mediatype is None:
raise NotAcceptable()
if mediatype in self.representations:
resp = self.representations[mediatype](data, *args, **kwargs)
resp.headers['Content-Type'] = mediatype
return resp
elif mediatype == 'text/plain':
resp = original_flask_make_response(str(data), *args, **kwargs)
resp.headers['Content-Type'] = 'text/plain'
return resp
else:
raise InternalServerError()
def mediatypes(self):
"""Returns a list of requested mediatypes sent in the Accept header"""
return [h for h, q in sorted(request.accept_mimetypes,
key=operator.itemgetter(1), reverse=True)]
def dispatch_request(self, *args, **kwargs):
# Taken from flask
#noinspection PyUnresolvedReferences
meth = getattr(self, request.method.lower(), None)
if meth is None and request.method == 'HEAD':
meth = getattr(self, 'get', None)
assert meth is not None, 'Unimplemented method %r' % request.method
for decorator in self.method_decorators:
meth = decorator(meth)
resp = meth(*args, **kwargs)
if isinstance(resp, ResponseBase): # There may be a better way to test
return resp
representations = self.representations or OrderedDict()
#noinspection PyUnresolvedReferences
mediatype = request.accept_mimetypes.best_match(representations, default=None)
if mediatype in representations:
data, code, headers = unpack(resp)
resp = representations[mediatype](data, code, headers)
resp.headers['Content-Type'] = mediatype
return resp
return resp