Flask请求和应用程序/json内容类型

2024-06-11 20:52:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个烧瓶应用程序,其视图如下:

@menus.route('/', methods=["PUT", "POST"])
def new():
    return jsonify(request.json)

但是,这只在请求的内容类型设置为application/json时有效,否则dictrequest.json为None。

我知道request.data将请求体作为字符串,但我不希望每次客户端忘记设置请求的内容类型时都将其解析为dict。

有没有办法假设每个传入请求的内容类型都是application/json?我只想始终能够访问有效的request.jsondict,即使客户端忘记将应用程序内容类型设置为json。


Tags: 视图json应用程序客户端类型内容烧瓶application
2条回答

使用^{}并将force设置为True

@menus.route('/', methods=["PUT", "POST"])
def new():
    return jsonify(request.get_json(force=True))

从文档中:

By default this function will only load the json data if the mimetype is application/json but this can be overridden by the force parameter.

Parameters:

  • force – if set to True the mimetype is ignored.

对于较旧的Flask版本,<;0.10,如果您希望宽容并允许JSON,那么始终可以自己进行解码,显式地:

from flask import json

@menus.route('/', methods=["PUT", "POST"])
def new():
    return jsonify(json.loads(request.data))

request对象已经有一个方法get_json,如果您使用force=True执行它,那么无论内容类型如何,它都可以为您提供json,因此您的代码如下所示:

@menus.route('/', methods=["PUT", "POST"])
def new():
    return jsonify(request.get_json(force=True))

实际上,烧瓶文档中说应该使用request.get_json,而不是request.jsonhttp://flask.pocoo.org/docs/api/?highlight=json#flask.Request.json

相关问题 更多 >