flask-restful是flask模块的一个扩展,能够快速构建restful风格的api。对于其他的扩展也有很高的兼容性。
安装flask_restful
pip install flask_restful
简单使用
from flask import Flask
from flask_restful import Resource, Api app = Flask(__name__)
api = Api(app) class TestRestful(Resource):
def get(self):
return {'hello': 'restful'} api.add_resource(TestRestful, '/') if __name__ == '__main__':
app.run()

演示结果

C:\Users\jh>curl http://127.0.0.1:5000/
{"hello": "restful"}

Flask-RESTful 提供的主要构建块是资源。资源构建在 Flask 可插入视图之上,
只需在资源上定义方法,就可以轻松访问多个 HTTP 方法。一个 todo 应用程序的基本 CRUD 资源是这样的:

from flask import Flask, request
from flask_restful import Resource, Api app = Flask(__name__)
api = Api(app)
todos = {} class TodoSimple(Resource):
def get(self, todo_id):
return {todo_id: todos[todo_id]} def put(self, todo_id):
todos[todo_id] = request.form['data']
return {todo_id: todos[todo_id]} api.add_resource(TodoSimple, '/<string:todo_id>') if __name__ == '__main__':
app.run()

 演示结果

执行
curl http://127.0.0.1:5000/todo1 -d "data=hello restful" -X put
返回 {"todo1": "hello restful"}
执行 curl http://127.0.0.1:5000/todo1
返回 {"todo1": "hello restful"}
curl http://127.0.0.1:5000/todo2 -d "data=good restful" -X put
返回 {"todo2": "good restful"}
执行 curl http://127.0.0.1:5000/todo2
返回 {"todo2": "good restful"}

Restful 能够从 view 方法中理解多种返回值。类似于 Flask,你可以返回任何可迭代的并且它将被转换成一个响应,
包括原始 Flask 响应对象。还支持使用多个返回值设置响应代码和响应头,如下所示:

from flask import Flask
from flask_restful import Resource, Api app = Flask(__name__)
api = Api(app) class Todo1(Resource):
def get(self):
return {'msg': 'hello restful'} class Todo2(Resource):
def get(self):
return {'msg': 'hello restful'}, 201 class Todo3(Resource):
def get(self):
return {'msg': 'hello restful'}, 201, {'new_tag': 'this is new_tag'} api.add_resource(Todo1, '/todo1')
api.add_resource(Todo2, '/todo2')
api.add_resource(Todo3, '/todo3')
if __name__ == '__main__':
app.run()

  演示结果

C:\Users\jh>curl -i http://127.0.0.1:5000/todo1
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 25
Server: Werkzeug/2.0.1 Python/3.8.6
Date: Tue, 16 Aug 2022 10:25:25 GMT

{"msg": "hello restful"} # return 的msg

很多时候,在一个 API 中,你的资源会有多个 url。可以将多个 url 传递给 Api 对象上的 add _ resource ()方法。
每一个都将被路由到Resource

from flask import Flask
from flask_restful import Resource, Api app = Flask(__name__)
api = Api(app) class TestRestful(Resource):
def get(self):
return {'hello': 'restful'} class Todo(Resource):
def get(self, todo_id):
return {'msg': 'hello todo'} api.add_resource(TestRestful, '/', '/test')
api.add_resource(Todo, '/todo/<int:todo_id>', endpoint='todo_ep') if __name__ == '__main__':
app.run()

  演示结果

C:\Users\jh>curl -i http://127.0.0.1:5000/todo2
HTTP/1.0 201 CREATED # return的状态码
Content-Type: application/json
Content-Length: 25
Server: Werkzeug/2.0.1 Python/3.8.6
Date: Tue, 16 Aug 2022 10:25:27 GMT

{"msg": "hello restful"} # return 的msg

C:\Users\jh>curl -i http://127.0.0.1:5000/todo3
HTTP/1.0 201 CREATED # return的状态码
Content-Type: application/json
Content-Length: 25
new_tag: this is new_tag #return 的new_tag
Server: Werkzeug/2.0.1 Python/3.8.6
Date: Tue, 16 Aug 2022 10:25:32 GMT

{"msg": "hello restful"} # return 的msg

C:\Users\jh>curl -i http://127.0.0.1:5000/
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 21
Server: Werkzeug/2.0.1 Python/3.8.6
Date: Tue, 16 Aug 2022 10:58:32 GMT

{"hello": "restful"}

C:\Users\jh>curl -i http://127.0.0.1:5000/test
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 21
Server: Werkzeug/2.0.1 Python/3.8.6
Date: Tue, 16 Aug 2022 10:58:42 GMT

{"hello": "restful"}

C:\Users\jh>curl -i http://127.0.0.1:5000/todo/1
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 22
Server: Werkzeug/2.0.1 Python/3.8.6
Date: Tue, 16 Aug 2022 10:59:02 GMT

{"msg": "hello todo"}

C:\Users\jh>curl -i http://127.0.0.1:5000/todo/2
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 22
Server: Werkzeug/2.0.1 Python/3.8.6
Date: Tue, 16 Aug 2022 10:59:06 GMT

{"msg": "hello todo"}

虽然 Flask 可以方便地访问请求数据(即 querystring 或 POST 表单编码的数据) ,
但验证表单数据仍然是一件痛苦的事情。使用类似于 argparse 的库对请求数据验证提供内置支持。

from flask import Flask
from flask_restful import reqparse, Resource, Api
app = Flask(__name__)
api = Api(app) parser = reqparse.RequestParser()
parser.add_argument('rate', type=int, help='rate to change for this resource') class Todo(Resource):
def post(self):
args = parser.parse_args()
print('args: %s' % args)
return {'msg': 'hello333 restful'} def get(self):
args = parser.parse_args()
print('args: %s' % args)
return {'msg': 'hello444 restful'} api.add_resource(Todo, '/todos') if __name__ == '__main__':
app.run(debug=True)

  演示结果

使用curl时,-d 后面的参数需要用双引号,否则可能获取不到参数
C:\Users\jh>curl -H "charset=utf-8" -d 'rate=110' http://127.0.0.1:5000/todos
{
"msg": "hello333 restful"
}

C:\Users\jh>curl -d "rate=123" http://127.0.0.1:5000/todos
{
"msg": "hello333 restful"
}

C:\Users\jh>curl -d "rate=123s" http://127.0.0.1:5000/todos
{
"message": {
"rate": "rate to change for this resource"
}
}

C:\Users\jh>curl http://127.0.0.1:5000/todos?rate=234
{
"msg": "hello444 restful"
}

C:\Users\jh>curl http://127.0.0.1:5000/todos?rate2=234
{
"msg": "hello444 restful"
}
服务端日志
127.0.0.1 - - [18/Aug/2022 11:04:44] "POST /todos HTTP/1.1" 200 -
args: {'rate': None}
127.0.0.1 - - [18/Aug/2022 11:04:51] "POST /todos HTTP/1.1" 200 -
args: {'rate': None}
127.0.0.1 - - [18/Aug/2022 11:04:54] "POST /todos HTTP/1.1" 200 -
args: {'rate': 123}
127.0.0.1 - - [18/Aug/2022 11:05:30] "POST /todos HTTP/1.1" 400 -
args: {'rate': 234}
127.0.0.1 - - [18/Aug/2022 11:06:08] "GET /todos?rate=234 HTTP/1.1" 200 -
127.0.0.1 - - [18/Aug/2022 11:06:12] "GET /todos?rate2=234 HTTP/1.1" 200 -
args: {'rate': None}

默认情况下,在你的返回迭代中所有字段将会原样呈现。尽管当你刚刚处理 Python 数据结构的时候,觉得这是一个伟大的工作,
但是当实际处理它们的时候,会觉得十分沮丧和枯燥。为了解决这个问题,Flask-RESTful 提供了 fields 模块和 marshal_with() 装饰器。
类似 Django ORM 和 WTForm,你可以使用 fields 模块来在你的响应中格式化结构。

from flask import Flask
from flask_restful import Resource, Api, fields, marshal_with
app = Flask(__name__)
api = Api(app) resource_fields = {
'task': fields.String,
'uri': fields.Url('todo')
} class TodoDao(object):
def __init__(self, todo_id, task):
self.todo_id = todo_id
self.task = task
self.status = 'active' class Todo(Resource):
@marshal_with(resource_fields)
def get(self, **kwargs):
return TodoDao(todo_id='my_todo', task='watch the car') api.add_resource(Todo, '/todo') if __name__ == '__main__':
app.run(debug=True)

  

C:\Users\jh>curl http://127.0.0.1:5000/todo
{
"task": "watch the car",
"uri": "/todo"
}

from flask import Flask
from flask_restful import Resource, Api, reqparse, abort
app = Flask(__name__)
api = Api(app) TODOS = {
'todo1': {'task': 'build an api'},
'todo2': {'task': '??????'},
'todo3': {'task': 'profit!'},
} def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id))
parser = reqparse.RequestParser()
parser.add_argument('task') class Todo(Resource):
def get(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
return TODOS[todo_id] def delete(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
del TODOS[todo_id]
return '', 204
def put(self, todo_id):
args = parser.parse_args()
task = {'task': args['task']}
TODOS[todo_id] = task
return task, 201 class TodoList(Resource):
def get(self, **kwargs):
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 api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>') if __name__ == '__main__':
app.run(debug=True)

  演示结果

C:\Users\jh>curl http://127.0.0.1:5000/todos
{
"todo1": {
"task": "build an api"
},
"todo2": {
"task": "??????"
},
"todo3": {
"task": "profit!"
}
}

C:\Users\jh>curl http://127.0.0.1:5000/todos/todo3
{
"task": "profit!"
}

C:\Users\jh>curl http://127.0.0.1:5000/todos/todo4
{
"message": "Todo todo4 doesn't exist"
}

C:\Users\jh>curl http://localhost:5000/todos/todo2 -X DELETE -v
* Trying 127.0.0.1:5000...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> DELETE /todos/todo2 HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.83.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
* HTTP 1.0, assume close after body
< HTTP/1.0 204 NO CONTENT
< Content-Type: application/json
< Server: Werkzeug/2.0.1 Python/3.8.6
< Date: Thu, 18 Aug 2022 06:10:09 GMT
<
* Closing connection 0

C:\Users\jh>curl http://127.0.0.1:5000/todos/todo2
{
"message": "Todo todo2 doesn't exist"
}

C:\Users\jh>curl http://localhost:5000/todos -d "task=something new" -X POST -v
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying 127.0.0.1:5000...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> POST /todos HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.83.1
> Accept: */*
> Content-Length: 18
> Content-Type: application/x-www-form-urlencoded
>
* Mark bundle as not supporting multiuse
* HTTP 1.0, assume close after body
< HTTP/1.0 201 CREATED
< Content-Type: application/json
< Content-Length: 32
< Server: Werkzeug/2.0.1 Python/3.8.6
< Date: Thu, 18 Aug 2022 06:10:53 GMT
<
{
"task": "something new"
}
* Closing connection 0

C:\Users\jh>curl http://127.0.0.1:5000/todos/todo4
{
"task": "something new"
}

C:\Users\jh>curl http://localhost:5000/todos/todo3 -d "task=something different" -X PUT -v
* Trying 127.0.0.1:5000...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> PUT /todos/todo3 HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.83.1
> Accept: */*
> Content-Length: 24
> Content-Type: application/x-www-form-urlencoded
>
* Mark bundle as not supporting multiuse
* HTTP 1.0, assume close after body
< HTTP/1.0 201 CREATED
< Content-Type: application/json
< Content-Length: 38
< Server: Werkzeug/2.0.1 Python/3.8.6
< Date: Thu, 18 Aug 2022 06:15:31 GMT
<
{
"task": "something different"
}
* Closing connection 0

C:\Users\jh>curl http://127.0.0.1:5000/todos/todo3
{
"task": "something different"
}

C:\Users\jh>curl http://127.0.0.1:5000/todos
{
"todo1": {
"task": "build an api"
},
"todo3": {
"task": "something different"
},
"todo4": {
"task": "something new"
}
}

 

flask-restful使用指南的更多相关文章

  1. Python Flask Restful

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

  2. 使用swagger 生成 Flask RESTful API

    使用swagger 生成 Flask RESTful API http://www.voidcn.com/article/p-rcvzjvpf-e.html swagger官网 https://swa ...

  3. Flask restful源码分析

    Flask restful的代码量不大,功能比较简单 参见 http://note.youdao.com/noteshare?id=4ef343068763a56a10a2ada59a019484

  4. 如何用rflask快速初始化Flask Restful项目

    如何用rflask快速初始化Flask Restful项目 说明 多啰嗦两句 我们在创建flask项目的时候,使用pycharm创建出来的项目比较简陋,而且随着项目的功能完善,项目目录结构会比较多,多 ...

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

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

  6. 快速创建Flask Restful API项目

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

  7. python Flask restful框架

    框架地址:https://github.com/flask-restful/flask-restful 文档:http://flask-restful.readthedocs.io/en/0.3.5/ ...

  8. Flask RESTful API搭建笔记

    之前半年时间,来到项目的时候,已经有一些东西,大致就是IIS+MYSQL+PHP. 所以接着做,修修补补,Android/iOS与服务器数据库交换用PHP, Web那边则是JS+PHP,也没有前后端之 ...

  9. 七十八:flask.Restful之flask-Restful标准化返回参数以及准备数据

    对于一个视图函数,可以指定好数据结构和字段用于返回,以后使用ORM模型或者自定义的模型的时候,它会自动获取模型中相应的字段,生成json数据,然后再返回给前端,这需要导入flask_restful.m ...

  10. Flask Restful Small Demo

    参考: http://www.pythondoc.com/flask-restful/first.html 什么是Rest Client-Server:服务器端与客户端分离. Stateless(无状 ...

随机推荐

  1. JavaScript之parseInt()方法

    parseInt(string, radix):用于解析一个字符串并返回指定基数的十进制整数或者NaN string参数为被解析的值,如果该值不是一个字符串,则会隐式的使用toString()方法转化 ...

  2. 基于BPM的低代码开发平台应具备什么功能

    一个BPM平台应该具备什么样的功能    用户在选型BPM软件的时候往往不知道该关注哪些功能,什么样的BPM软件能满足国内企业应用需求,笔者从多年BPM研发和实施经验提炼了中国特色BPM应该具备的功能 ...

  3. awk运用三维数组进行插值获得任意经纬度处的水层沉积层地壳厚度

    awk三维数组与插值 目的:给定经纬度,获得该点地下的冰层水层沉积层和地壳的厚度 实现:awk一行命令 下载Crust1.0模型 该数据集的详细介绍见官网. 解压后有几个文件:crust1.vp,cr ...

  4. 我熬夜开发了一款简约实用、支持多平台的Markdown在线编辑器(开源)

    前言 之前,一直想开发一款属于自己的Markdown编辑器,主要是自己平常写文章可以更加灵活操作,另外扩宽自己的视野也是非常不错的选择啊!所以在周末就决定玩耍一番.首先我调研了很多线上热门的md编辑器 ...

  5. SAP APO-供需匹配

    供需匹配包含主要功能"匹配能力"(CTM)和一个用于分配库存的附加功能. 在高级计划和优化中,SDM组件为这些应用程序提供跨工厂供应策略- 生产计划和详细计划(PP / DS) 供 ...

  6. kali 漏洞扫描

    前言 漏洞扫描器是一种能够自动在计算机.信息系统.网络及应用软件中寻找和发现安全弱点的程序.它通过网络对目录系统进行探测,向目标系统发送数据,并将反馈数据与自带的漏洞特征库进行匹配,进而列举目标系统上 ...

  7. TopoLVM: 基于LVM的Kubernetes本地持久化方案,容量感知,动态创建PV,轻松使用本地磁盘

    正文 研发测试场景下,一般追求的是一键快速起环境,横向动态复制,一人一套,随起随用,用完即走.作为使用方,其不用关心实际的物理资源是怎样的,环境起在哪里,只要声明自己的使用需求即可.但作为方案构建者以 ...

  8. Spring框架系列(8) - Spring IOC实现原理详解之Bean实例化(生命周期,循环依赖等)

    上文,我们看了IOC设计要点和设计结构:以及Spring如何实现将资源配置(以xml配置为例)通过加载,解析,生成BeanDefination并注册到IoC容器中的:容器中存放的是Bean的定义即Be ...

  9. Python爬取某网站文档数据完整教程(附源码)

    基本开发环境 (https://jq.qq.com/?_wv=1027&k=NofUEYzs) Python 3.6 Pycharm 相关模块的使用 (https://jq.qq.com/?_ ...

  10. 抓到 Netty 一个隐藏很深的内存泄露 Bug | 详解 Recycler 对象池的精妙设计与实现

    欢迎关注公众号:bin的技术小屋,如果大家在看文章的时候发现图片加载不了,可以到公众号查看原文 本系列Netty源码解析文章基于 4.1.56.Final版本 最近在 Review Netty 代码的 ...