Flask-restful Request parsing

Source: Internet
Author: User

Basic parameters

 fromFlaskImportFlask fromFlask.ext.restfulImportreqparse, Abort, Api, Resourceapp= Flask (__name__) API=Api (APP) TODOS= {'Todo1': {'Task':'Build an API'},    'Todo2': {'Task':'?????'},    'Todo3': {'Task':'profit!'},}parser=Reqparse. Requestparser () parser.add_argument ('Task', Type=str, help='Rate cannot be converted') parser.add_argument (' Rate', type=int)defabort_if_todo_doesnt_exist (todo_id):iftodo_id not inchTodos:abort (404, message="Todo {} doesn ' t exist". Format (todo_id))#ToDoList#shows a list of all Todos, and lets your POST to add new tasksclasstodolist (Resource):defGet (self):returnTODOSdefpost (self): args=Parser.parse_args () todo_id= Int (max (Todos.keys ()). Lstrip ('Todo')) + 1todo_id='todo%i'%todo_id todos[todo_id]= {'Task': args['Task']}        returnTODOS[TODO_ID], 201#### actually setup the API resource routing here##Api.add_resource (ToDoList,'/todos')if __name__=='__main__': App.run (Debug=true)

Key code

Parser = Reqparse. Requestparser () parser.add_argument ('task', type=str, help='rate Cannot is converted') parser.add_argument ('rate', type=  = Parser.parse_args ()

The help information is specified and is rendered as an error message when parsing the type error, otherwise the default returns the error of the type error itself.

Required Parameters

Add condition

whole2.py

 fromFlaskImportFlask fromFlask.ext.restfulImportreqparse, Abort, Api, Resourceapp= Flask (__name__) API=Api (APP) TODOS= {'Todo1': {'Task':'Build an API'},    'Todo2': {'Task':'?????'},    'Todo3': {'Task':'profit!'},}parser=Reqparse. Requestparser () parser.add_argument ('Task', Type=str, help='Rate cannot be converted') parser.add_argument (' Rate', Type=int, required=Ture)defabort_if_todo_doesnt_exist (todo_id):iftodo_id not inchTodos:abort (404, message="Todo {} doesn ' t exist". Format (todo_id))#ToDoList#shows a list of all Todos, and lets your POST to add new tasksclasstodolist (Resource):defGet (self):returnTODOSdefpost (self): args=Parser.parse_args () todo_id= Int (max (Todos.keys ()). Lstrip ('Todo')) + 1todo_id='todo%i'%todo_id todos[todo_id]= {'Task': args['Task']}        returnTODOS[TODO_ID], 201#### actually setup the API resource routing here##Api.add_resource (ToDoList,'/todos')if __name__=='__main__': App.run (Debug=true)

Key code

Parser.add_argument (' rate ', Type=int, Required=ture)

Run

Python whole2.py

Another window executes

[Email protected]:~/project/flask$ Curl 127.0.0.1:5000/todos-d task=hello-x post{    "message": {        "rate": " Missing required parameter in the JSON body or the post body or the query string "    }}

Add the rate parameter and then execute it, OK.

[Email protected]:~/project/flask$ Curl 127.0.0.1:5000/todos-d task=hello-d rate=3-x post{    "task": "Hello"}
Multiple Values & lists

whole3.py

 fromFlaskImportFlask fromFlask.ext.restfulImportreqparse, Abort, Api, Resourceapp= Flask (__name__) API=Api (APP) TODOS= {'Todo1': {'Task':'Build an API'},    'Todo2': {'Task':'?????'},    'Todo3': {'Task':'profit!'},}parser=Reqparse. Requestparser () parser.add_argument ('Task', Type=str, action='Append')defabort_if_todo_doesnt_exist (todo_id):iftodo_id not inchTodos:abort (404, message="Todo {} doesn ' t exist". Format (todo_id))#ToDoList#shows a list of all Todos, and lets your POST to add new tasksclasstodolist (Resource):defGet (self):returnTODOSdefpost (self): args=Parser.parse_args () todo_id= Int (max (Todos.keys ()). Lstrip ('Todo')) + 1todo_id='todo%i'%todo_id todos[todo_id]= {'Task': args['Task']}        returnTODOS[TODO_ID], 201#### actually setup the API resource routing here##Api.add_resource (ToDoList,'/todos')if __name__=='__main__': App.run (Debug=true)

Perform

Python whole3.py

Another window executes

[Email protected]:~/project/flask$ Curl 127.0.0.1:5000/todos-d task=hello-d task=hello2-d task=hello4-x POST{    "ta SK ": [        " Hello ",         " Hello2 ",         " Hello4 "    ]}

Browser Open Results

{"    Todo1": {        "task": "Build an API"    },     "Todo2": {        "task": "?????"    },     "Todo3": {        "Task": "Profit!"    },     "Todo4": {"        task": [            "Hello",             "Hello2",             "Hello4"        ]    } }
Parameter position

Pending resolution: HTTP://WWW.PYTHONDOC.COM/FLASK-RESTFUL/REQPARSE.HTML#ID5

  

  

Flask-restful Request resolution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.