Python flask.request 模块,accept_mimetypes() 实例源码

我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用flask.request.accept_mimetypes()

项目:quizbot-2017    作者:pycontw    | 项目源码 | 文件源码
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
项目:lama    作者:CSE-POST    | 项目源码 | 文件源码
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"]
项目:drift    作者:dgnorth    | 项目源码 | 文件源码
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
项目:gatekeeper    作者:otto-de    | 项目源码 | 文件源码
def request_wants_json():
    for mime in request.accept_mimetypes:
        if 'json' in mime[0]:
            return mime[0]
    return False
项目:do-portal    作者:certeu    | 项目源码 | 文件源码
def before_auth_request():
    if 'application/json' not in request.accept_mimetypes:
        return errors.not_acceptable()
项目:do-portal    作者:certeu    | 项目源码 | 文件源码
def before_api_request():
    if 'application/json' not in request.accept_mimetypes:
        return errors.not_acceptable()
项目:do-portal    作者:certeu    | 项目源码 | 文件源码
def before_api_request():
    if 'application/json' not in request.accept_mimetypes:
        return errors.not_acceptable()
项目:gwot-physical    作者:JanVan01    | 项目源码 | 文件源码
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']
项目:flask-graphql    作者:graphql-python    | 项目源码 | 文件源码
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']
项目:tripoli    作者:DDMAL    | 项目源码 | 文件源码
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)
项目:NZ-ORCID-Hub    作者:Royal-Society-of-New-Zealand    | 项目源码 | 文件源码
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)
项目:logistics-wizard-controller    作者:IBM-Cloud    | 项目源码 | 文件源码
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']
项目:url-shortener-api    作者:mabbie    | 项目源码 | 文件源码
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'])
项目:locust-demo    作者:bmd    | 项目源码 | 文件源码
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()
项目:locust-demo    作者:bmd    | 项目源码 | 文件源码
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)]
项目:locust-demo    作者:bmd    | 项目源码 | 文件源码
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
项目:SKEDD    作者:CameronOC    | 项目源码 | 文件源码
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']
项目:noobotkit    作者:nazroll    | 项目源码 | 文件源码
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()
项目:noobotkit    作者:nazroll    | 项目源码 | 文件源码
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)]
项目:noobotkit    作者:nazroll    | 项目源码 | 文件源码
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
项目:Chorus    作者:DonaldBough    | 项目源码 | 文件源码
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()
项目:Chorus    作者:DonaldBough    | 项目源码 | 文件源码
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)]
项目:Chorus    作者:DonaldBough    | 项目源码 | 文件源码
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