简体   繁体   English

Flask-restful:如何只响应请求('Accept':'application / json')?

[英]Flask-restful: How to only response to requests come with ('Accept':'application/json')?

I have a json api APP, working well.Now I want it only accept and response json, not response to text/html request. 我有一个json api APP,运行良好。现在我希望它只接受和响应json,而不是对text / html请求的响应。 App looks like this: 应用程序如下所示:

class Books(Resource):
    def get(self):
        return json.dumps(data)

Someone can help? 有人可以帮忙吗? Thanks. 谢谢。

You could use a preprocessing request handler to reject all request with the wrong MimeType. 您可以使用预处理请求处理程序拒绝具有错误MimeType的所有请求。 There is a property of the Request object (not documented tought, but present at least on Flask 0.10) named is_json Request对象的属性(没有记录,但至少在Flask 0.10上出现)名为is_json

Given your Flask app is called application, you could use something like : 鉴于您的Flask应用程序称为应用程序,您可以使用以下内容:

from flask import request, abort, jsonify

@application.before_request
def only_json():
    if not request.is_json: 
        abort(400)  # or any custom BadRequest message

I would also use the Flask jsonify function to build your reponse, it will ensure that the response is well formatted in json, and also sets the right headers. 我还会使用Flask jsonify函数来构建你的响应,它将确保响应在json中格式良好,并且还设置了正确的标题。

class Books(Resource):
    def get(self):
        return jsonify(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM