Flask请求和应用程序/ json内容类型 [英] Flask request and application/json content type

查看:137
本文介绍了Flask请求和应用程序/ json内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下视图的瓶子应用程序:

I have a flask app with the following view:

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

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

However, this only works if the request's content type is set to application/json, otherwise the dict request.json is None.

我知道 request.data 将请求体作为字符串,但是我不想在客户端忘记设置请求的内容类型时将其解析为一个dict。

I know that request.data has the request body as a string, but I don't want to be parsing it to a dict everytime a client forgets to set the request's content-type.

有没有办法假设每个进入请求的内容类型是 application / json ?所有我想要的是始终可以访问一个有效的 request.json dict,即使客户端忘记将应用程序内容类型设置为json。

Is there a way to assume that every incoming request's content-type is application/json? All I want is to always have access to a valid request.json dict, even if the client forgets to set the application content-type to json.

推荐答案

Flask 0.10 ,您可以使用 request.get_json() 并将强制设置为 True

As of Flask 0.10, you can use request.get_json() and set force to True:

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

从文档中:


默认情况下,如果mimetype为 application / json ,但这可以被强制参数覆盖。

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.

参数:


  • 强制 - 如果设置为 True ,则忽略mimetype。

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

对于旧版本,如果您想要原谅并允许使用JSON,请始终,您可以自己解释:

For older versions, if you want to be forgiving and allow for JSON, always, you can do the decode yourself, explictly:

import json

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

这篇关于Flask请求和应用程序/ json内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆