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 ...
随机推荐
- EIP权限工作流平台-升级说明(2018-12-04)
表单生成器,文本框新增验证(默认验证及正则表达式) 列表查询支持复杂查询,支持文本框,下拉框,时间查询
- SQL 全角半角转换-(摘抄)
/****** SQL转换全角/半角函数 开始******/ CREATE FUNCTION ConvertWordAngle ( @str NVARCHAR(4000), --要转换的字符串 @fl ...
- .NET和C#的版本历史
维基百科页面:https://en.wikipedia.org/wiki/.NET_Framework_version_history Versionnumber CLRversion Release ...
- Socket 简易静态服务器 WPF MVVM模式(二)
command类 标准来说,command会有三种模式,委托命令 准备命令 附加命令 1.DelegateCommand 2.RelayCommand 3.AttachbehaviorCommand ...
- ios app提交之前需要哪几个证书
1.遇到的问题 一款App在别人的机器上开发和发布,现在迭代更新和开发需要在一台新mac机上开发和发布. (使用同一个开发者账号)问题: 1.在新mac机器上开发并导入真机测试,是不是需要从别人的机器 ...
- 泛型1(一些algorithm函数)
泛型算法本身不会执行容器的操作,它们只会运行于迭代器之上,执行迭代器的操作.因此算法可能改变容器中保存的元素,也可能在容器内移动元素,但永远不会直接添加或删除元素. 只读算法: accumulate: ...
- python中一些算法数列
斐波那契数列: 1 def fn(n): 2 if n==1: 3 return 1 4 elif n==2: 5 return 1 6 else: 7 return fn(n-1)+fn(n-2) ...
- 伪元素改变date类型input框的默认样式实例页面
CSS代码: ::-webkit-datetime-edit { padding: 1px; background: url(/study/image/selection.gif); } ::-web ...
- 百度地图中使用mouseover事件获取经纬度时无法拿到鼠标所在位置的经纬度。
用百度2.0的话使用mousemove 鼠标在地图区域移动过程中触发此事件.mouseover参数e中没有point参数
- 【转】LAMBDAFICATOR: Crossing the gap from imperative to functional programming through refactorings
Link:http://refactoring.info/tools/LambdaFicator/ Problem Description Java 8 will support lambda exp ...