RESTful-Flask parsing JSON Arrays with parse_args()

旧街凉风 提交于 2020-03-02 07:44:10

问题


This's my code:

parser = reqparse.RequestParser(bundle_errors=True)    
parser.add_argument('list', type=list, location="json")

class Example(Resource):
    def post(self):
        #json_data = request.get_json(force=True)
        json_data = parser.parse_args()
        return json_data

If I post a JSON object like this:

{
  "list" : ["ele1", "ele2", "ele3"]
}

parser.parse_args() parses it to this python list:

'list': ['e','l','e','1']

request.get_json() works, but I would really like to have the validation of the reqparser... How can I get the parser.parse_args() working properly with JSON arrays?

(I get this error: TypeError("'int' object is not iterable",) is not JSON serializable, if if the JSON array contains integers: 'list': [1, 2, 3])


回答1:


chuong nguyen is right in his comment to your question. With an example:

def post(self):
    parser = reqparse.RequestParser()
    parser.add_argument('options', action='append')
    parser = parser.parse_args()
    options = parser['options']

    response = {'options': options}
    return jsonify(response)

With this, if you request:

curl -H 'Content-type: application/json' -X POST -d '{"options": ["option_1", "option_2"]}' http://127.0.0.1:8080/my-endpoint

The response would be:

{
    "options": [
      "option_1",
      "option_2"
    ]
}



回答2:


Here is a workaround a came up with. But it really seems like a big hack to me...

By extending the input types you can create your own "array type" like that:

from flask import request

def arrayType(value, name):
    full_json_data = request.get_json()
    my_list = full_json_data[name]
    if(not isinstance(my_list, (list))):
        raise ValueError("The parameter " + name + " is not a valid array")
    return my_list

and than use it with the parser:

parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('list', type=arrayType, location="json")

It works, but I think there should be a proper way to do this within flaks-restful. I imagine calling request.get_json() for each JSON array is also not the best in terms of performance, especially if the request data is rather big.



来源:https://stackoverflow.com/questions/45613160/restful-flask-parsing-json-arrays-with-parse-args

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!