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 ...
随机推荐
- webrequest、httpwebrequest、webclient、HttpClient 四个类的区别
一.在 framework 开发环境下: webrequest.httpwebreques 都是基于Windows Api 进行包装, webclient 是基于webrequest 进行包装:(经 ...
- WPF MultiSelect模式下ListBox 实现多个ListBoxItem拖拽
WPF 的ListBox不支持很多常见的用户习惯,如在Explorer中用鼠标可以选择多项Item,并且点击已经选择的Item,按住鼠标左键可以将所有已选择Item拖拽到指定的位置.本文简单的实现了这 ...
- 分享我访问google的方法
对于程序员来说,有很多技术问题还是通过互联网搜索来解决的.所以百度.google对于我们是多少的重要.但是GOOGLE现在无法访问了.怎么办呢.以下是我访问google的方法. 首先自己制作了一个简单 ...
- SQLServer备份恢复助手(太强大了!)
下载地址: http://download.csdn.net/detail/gguozhenqian/8105779
- 「BZOJ 5188」「Usaco2018 Jan」MooTube
题目链接 luogu bzoj \(Describe\) 有一个\(n\)个节点的树,边有权值,定义两个节点之间的距离为两点之间的路径上的最小边权 给你\(Q\)个询问,问你与点\(v\)的距离大于等 ...
- linking against a dylib which is not safe for use in application extensions
完成到这里可能会出现警告 linking against a dylib which is not safe for use in application extensions 解决办法:
- GitHub+Hexo 搭建个人网站详细教程
原文链接 GitHub+Hexo 搭建个人网站详细教程 前言: 随着互联网浪潮的翻腾,国内外涌现出越来越多优秀的社交网站让用户分享信息更加便捷.然后,如果你是一个不甘寂寞的程序猿(媛),是否也想要搭建 ...
- Bootstrap 基本css样式
1.标题1级标题<h1> 38px 是默认大小的2.7倍2级标题<h2> 32px 是默认大小的2.25倍3级标题<h3> 24px 是默认大小的1.70倍4级标题 ...
- numpy.histogram 官方手册
numpy.histogram numpy.histogram(a, bins=10, range=None, normed=False, weights=None, density=None) Co ...
- 老男孩Day17作业:后台管理平台编辑表格
一.作业需求: 后台管理平台 ,编辑表格: 1. 非编辑模式: 可对每行进行选择: 反选: 取消选择 2. 编辑模式: 进入编辑模式时如果行被选中,则被选中的行万变为可编辑状态,未选中的不改变 退出编 ...