flask-restful 请求解析
基本参数
from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource app = 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) def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id)) # TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
def get(self):
return TODOS def post(self):
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201 ##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos') if __name__ == '__main__':
app.run(debug=True)
关键代码
parser = reqparse.RequestParser()
parser.add_argument('task', type=str, help='Rate cannot be converted')
parser.add_argument('rate', type=int) args = parser.parse_args()
指定了help信息,在解析类型错误的时候,就会作为错误信息呈现出来;否则默认返回类型错误本身的错误。
必须的参数
添加条件
whole2.py
from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource app = 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) def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id)) # TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
def get(self):
return TODOS def post(self):
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201 ##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos') if __name__ == '__main__':
app.run(debug=True)
关键代码
parser.add_argument('rate', type=int, required=Ture)
运行
python whole2.py
另一个窗口执行
jihite@ubuntu:~/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"
}
}
添加rate参数再执行,就ok了
jihite@ubuntu:~/project/flask$ curl 127.0.0.1:5000/todos -d task=hello -d rate=3 -X POST
{
"task": "hello"
}
多个值&列表
whole3.py
from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource app = 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') def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id)) # TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
def get(self):
return TODOS def post(self):
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201 ##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos') if __name__ == '__main__':
app.run(debug=True)
执行
python whole3.py
另一窗口执行
jihite@ubuntu:~/project/flask$ curl 127.0.0.1:5000/todos -d task=hello -d task=hello2 -d task=hello4 -X POST
{
"task": [
"hello",
"hello2",
"hello4"
]
}
浏览器打开结果
{
"todo1": {
"task": "build an API"
},
"todo2": {
"task": "?????"
},
"todo3": {
"task": "profit!"
},
"todo4": {
"task": [
"hello",
"hello2",
"hello4"
]
}
}
参数位置
# Look only in the POST body
parser.add_argument('name', type=int, location='form') # Look only in the querystring
parser.add_argument('PageSize', type=int, location='args') # From the request headers
parser.add_argument('User-Agent', type=str, location='headers') # From http cookies
parser.add_argument('session_id', type=str, location='cookies') # From file uploads
parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')
多个位置
parser.add_argument('text', location=['headers', 'values'])
列表中最后一个优先出现在结果集中。(例如:location=[‘headers’, ‘values’],解析后 ‘values’ 的结果会在 ‘headers’ 前面)
flask-restful 请求解析的更多相关文章
- Flask之 请求,应用 上下文源码解析
什么是上下文? 每一段程序都有很多外部变量.只有像Add这种简单的函数才是没有外部变量的.一旦你的一段程序有了外部变量,这段程序就不完整,不能独立运行.你为了使他们运行,就要给所有的外部变量一个一个写 ...
- Python Flask Restful
Flask Restful 1.flask restful 在flask基础上进行一些封装,主要用于实现restful接口 2.restful的理解 1)URI(统一资源标识符):每一个URI代表一 ...
- 【Flask-RESTPlus系列】Part3:请求解析
0x00 内容概览 请求解析 基本参数 必需参数 多值和列表 其他目标 参数位置 参数多个位置 高级类型处理 解析器继承 文件上传 错误处理 错误消息 参考链接 0x01 请求解析 注意:Flask- ...
- python 全栈开发,Day139(websocket原理,flask之请求上下文)
昨日内容回顾 flask和django对比 flask和django本质是一样的,都是web框架. 但是django自带了一些组件,flask虽然自带的组件比较少,但是它有很多的第三方插件. 那么在什 ...
- Flask的请求对象--request
request-Flask的请求对象 请求解析和响应封装大部分是有Werkzeug完成的,Flask子类化Werkzeug的请求(Request)对象和响应(Response)对象,并添加了和程序的特 ...
- flask源码解析之上下文为什么用栈
楔子 我在之前的文章<flask源码解析之上下文>中对flask上下文流程进行了详细的说明,但是在学习的过程中我一直在思考flask上下文中为什么要使用栈完成对请求上下文和应用上下文的入栈 ...
- day89 DjangoRsetFramework学习---restful规范,解析器组件,Postman等
DjangoRsetFramework学习---restful规范,解析器组件,Postman等 本节目录 一 预备知识 二 restful规范 三 DRF的APIView和解析 ...
- jmeter测试 flask 接口请求
jmeter测试 flask 接口请求 flask的代码如下: #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flas ...
- [flask]Restful接口测试简单的应用
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : shenqiang from flask import Flask,make_res ...
- 快速创建Flask Restful API项目
前言 Python必学的两大web框架之一Flask,俗称微框架.它只需要一个文件,几行代码就可以完成一个简单的http请求服务. 但是我们需要用flask来提供中型甚至大型web restful a ...
随机推荐
- 「POJ 1741」Tree
题面: Tree Give a tree with n vertices,each edge has a length(positive integer less than 1001). Define ...
- SSI简介 与 nginx开启SSI
Server Side Include : 服务器端嵌入 原理 : 将内容发送到浏览器之前,可以使用“服务器端包含 (SSI)”指令将文本.图形或应用程序信息包含到网页中.因为包含 SSI 指令的文件 ...
- 201621123012 《java程序设计》第2周学习总结
1. 本章学习总结 1.学习了java许多了基本语法,string函数,arraylist函数的各种功能方法和调用. 2.了解了除for循环之外的foreach循环 3.学习了各种数值类的包装 4.熟 ...
- day3学python 字典+列表集合+文件读取
字典+列表集合+文件读取 字典示例 ************************ 各地食品的三级菜单************************* 1.使用字典嵌套字典 2.采用死循环思路 3 ...
- 为什么要使用MQ消息中间件?
在面试大型互联网公司的时候,很可能会被问到消息队列的问题: 1.在何种场景下使用了消息中间件? 2.为什么要在系统里引入消息中间件? 3.如何实现幂等? 链式调用是我们在写程序时候的一般流程,为了完成 ...
- 帝国cms刷新内容页提示.phome_ecms_news_data_' doesn't exist
帝国cms后台刷新提示.phome_ecms_news_data_' doesn't exist解决方法: 刷新所有信息内容页面时提示“Table '*.phome_ecms_article_data ...
- HBASE常用操作增删改查
http://javacrazyer.iteye.com/blog/1186881 http://www.cnblogs.com/invban/p/5667701.html
- Python博文列表
手把手|100行Python代码自动抢火车票!(包教包会):https://zhuanlan.zhihu.com/p/32928355 最全中华古诗词数据库, :https://github.com/ ...
- 带权并查集 - How Many Answers Are Wrong
思路: 带权并查集+向量偏移 #include <iostream> using namespace std; int n, m; ]; ]; // 到根节点的距离 ; void init ...
- 三个常用的PHP图表类库
Jpgraph 只要把example中的require_once路径改了就放进来用吧,我下的是最新版的jpgraph-3.5.0b1,反正测试嘛,我记得跟3.0.7还是有差别的,把文件名都重新命名过了 ...