我对Flask(&Flask-RESTful)非常陌生.

My problem : json arguments for a POST is getting set to NONE (not working).

I am able to take arguments from the form-data, using POSTMAN plugin for chrome. But, when i switch to raw (& feed a json), it fails to read the json & assigns a NONE to all my arguments.

我读过一些与此相关的堆栈溢出帖子:link1,link2,link3.这些都没有帮到我.

我在Oracle Linux 6.5上使用python-2.6Flask-Restful-0.3.3Flask-0.10.1ChromePOSTMAN.

Python code app.py :

from flask import Flask, jsonify
from flask_restful import reqparse, abort, Api, Resource

app = Flask(__name__)
api = Api(app)

parser = reqparse.RequestParser()
parser.add_argument('username', type=str)
parser.add_argument('password', type=str)

class HelloWorld(Resource):
    def post(self):
        args = parser.parse_args()
        un = str(args['username'])
        pw = str(args['password'])
        return jsonify(u=un, p=pw)

api.add_resource(HelloWorld, '/testing')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5444 ,debug=True)

Testing this使用POSTMAN:

  • Using form-data : works perfectly !
  • Using raw -> json : causes this issue

Things tried #1:

Add json parameter to my add_argument() method in app.py

parser = reqparse.RequestParser()
parser.add_argument('username', type=str, location='json') # added json
parser.add_argument('password', type=str, location='json') # added json

Input:{"username":"hello","password":"world"}

Output:{p:"无","u:"无"}

Things tried #2 :

Change type to unicode in add_argument() method in app.py

parser = reqparse.RequestParser()
parser.add_argument('username', type=unicode, location='json') # change type to unicode
parser.add_argument('password', type=unicode, location='json') # change type to unicode

Input:{"username":"hello","password":"world"}

Output:{p:"无","u:"无"}


PS : I will keep updating my question, with every failed attempt. Please let me know if you need any more info to make this question more clear.

推荐答案

根据Request.json和新Request.get_json的文档,您应该将POST请求上的mimetype设置为application/json.这是Flask自动将您的JSON数据解析成Request.json属性的唯一方法,我相信这正是Flask-RESTful检索JSON数据所依赖的.

注意:较新的get_json函数有一个选项,可以强制将POST数据解析为JSON,而不考虑mimetype

Json相关问答推荐

jq不会为空输入返回非零

从JSON格式提取数据时分隔通用名称

使用快速json库编写json可以消除所有缩进

基于 JSON 字段的 Jolt 条件标志

jq如何合并两个json对象

在 python 中循环 JSON 数组

用于遮蔽卡的 Jolt 规格

我如何将 JSON 格式与 flutter 一起使用?帮助使用 Gamebanana api

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

如果 jq 数组中的字符串是对象或字符串,则获取值

向 JSON 文件添加注释

UTF-8 字符编码之战 json_encode()

将json字符反序列化为枚举

Jackson Scala 模块的小例子?

JSON对象中的JavaScript递归搜索

如何在 MVC4 中将 Json 字符串输出为 JsonResult?

使用 Retrofit 解析动态密钥 Json 字符串

如何在 Django JSONField 数据上聚合(最小/最大等)?

在播放框架 JsObject 中解析 Json 数组

Javascript对象和JSON对象有什么区别