基本参数

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 请求解析的更多相关文章

  1. Flask之 请求,应用 上下文源码解析

    什么是上下文? 每一段程序都有很多外部变量.只有像Add这种简单的函数才是没有外部变量的.一旦你的一段程序有了外部变量,这段程序就不完整,不能独立运行.你为了使他们运行,就要给所有的外部变量一个一个写 ...

  2. Python Flask Restful

    Flask  Restful 1.flask restful 在flask基础上进行一些封装,主要用于实现restful接口 2.restful的理解 1)URI(统一资源标识符):每一个URI代表一 ...

  3. 【Flask-RESTPlus系列】Part3:请求解析

    0x00 内容概览 请求解析 基本参数 必需参数 多值和列表 其他目标 参数位置 参数多个位置 高级类型处理 解析器继承 文件上传 错误处理 错误消息 参考链接 0x01 请求解析 注意:Flask- ...

  4. python 全栈开发,Day139(websocket原理,flask之请求上下文)

    昨日内容回顾 flask和django对比 flask和django本质是一样的,都是web框架. 但是django自带了一些组件,flask虽然自带的组件比较少,但是它有很多的第三方插件. 那么在什 ...

  5. Flask的请求对象--request

    request-Flask的请求对象 请求解析和响应封装大部分是有Werkzeug完成的,Flask子类化Werkzeug的请求(Request)对象和响应(Response)对象,并添加了和程序的特 ...

  6. flask源码解析之上下文为什么用栈

    楔子 我在之前的文章<flask源码解析之上下文>中对flask上下文流程进行了详细的说明,但是在学习的过程中我一直在思考flask上下文中为什么要使用栈完成对请求上下文和应用上下文的入栈 ...

  7. day89 DjangoRsetFramework学习---restful规范,解析器组件,Postman等

     DjangoRsetFramework学习---restful规范,解析器组件,Postman等           本节目录 一 预备知识 二 restful规范 三 DRF的APIView和解析 ...

  8. jmeter测试 flask 接口请求

    jmeter测试 flask 接口请求 flask的代码如下: #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flas ...

  9. [flask]Restful接口测试简单的应用

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : shenqiang from flask import Flask,make_res ...

  10. 快速创建Flask Restful API项目

    前言 Python必学的两大web框架之一Flask,俗称微框架.它只需要一个文件,几行代码就可以完成一个简单的http请求服务. 但是我们需要用flask来提供中型甚至大型web restful a ...

随机推荐

  1. 百度地图离线API及地图数据下载工具

    全面介绍,请看下列介绍地址,改写目前最新版本的百度V2.0地图,已全面实现离线操作,能到达在线功能的95%以上 http://api.jjszd.com:8081/apituiguang/gistg. ...

  2. Linux中,关闭selinux

    首先我们可以用命令来查看selinux的状态getenforce 这个命令可以查看到selinux的状态,当前可以看到是关闭状态的. 还有一个命令也可以查看出selinux的状态.sestatus - ...

  3. MultiTrigger

    MultiTrigger是多条件触发器.意为多个条件同时满足时才会触发. 用法和Trigger差不多. 但是MultiTrigger的条件是在写在自身的判断环境之中. 基本的语法是: <Mult ...

  4. 深入 Nginx:我们是如何为性能和规模做设计的

    NGINX 在网络应用中表现超群,在于其独特的设计.许多网络或应用服务器大都是基于线程或者进程的简单框架,NGINX突出的地方就在于其成熟的事件驱动框架,它能应对现代硬件上成千上万的并发连接. NGI ...

  5. python3关于date和time的标准库

    python3中关于日期和时间的标准库datetime和time,之前都是用的时候随用随查,今天系统的看一下用这两个库可以做些什么. 1.time标准库 #首先添加一个time对象,看一下该对象的属性 ...

  6. scrapy中通过set()方法进行数据过滤去重

    我们经常在抓取数据是碰到 数据重复的问题,除了radis数据库去重功能外,还有一种简便的过滤方法, 来来 我们直接上代码: pipelines.py中: from scrapy.exceptions ...

  7. LAMP课程

    LAMP课程 上次课回顾: ls -a:查看全部目录内容 若文件名以“.”开头,则认为是隐藏的文件. ls-l:可以直接用命令 ll命令:ls -l 的别名. ls -m:横向显示文件和目录 ls - ...

  8. docker镜像的创建

    获得更多资料欢迎进入我的网站或者 csdn或者博客园 昨天讲解了docker的安装与基本使用,今天给大家讲解下docker镜像的创建的方法,以及push到Docker Hub docker安装请点击右 ...

  9. linux上的那些查找的命令

    由于工作的需要,少不得要在linux系统上查找各种各样的文件,关于在linux查找的命令有不少,这里小小的总结下. 简单介绍下各个命令的用途: find:实际搜索硬盘查询文件名称: whereis:查 ...

  10. Unity---动画系统学习(4)---使用混合树(Blend Tree)来实现走、跑、转弯等的动画切换

    1. 介绍 Blend Tree用于多个动画之间的混合,比如走到跑的切换.转弯的切换. 如果用动画学习笔记(3)中的方法,需要新建很多的状态,不仅麻烦,而且切换状态时也很容易不流畅. 而Blend T ...