一、起步:

Flask-RESTful 是用于快速构建REST API 的Flask扩展

1、安装RESTful

pip install flask-restful

2、Hello World示例

from flask import Flask
from flask-restful import Resource, Api app = Flask(__name__)
api = Api(app) class HelloWorldResource(Resource):
def get(self):
return {"hello": "world"}
def post(self):
return {"msg": "post hello world"} api.add_resource(HelloWorldResource, "/") # 下面对于1.0之后的Flask可有可无
if __name__ == "__main__":
app.run(debug=True)

二、关于视图

  1、为路由起名

    通过endpoint参数为路由起名

api.add_resource(HelloWorldResource, "/", endpoint="HelloWorld")

  2、蓝图中使用

from flask import Flask
from flask_restful import Api, Resource app = Flask(__name__) user_bp = Blueprint("user", __name__) user_api = Api(user_bp) class UserProfileResource(Resource):
def get(self):
return {"msg": "get user profile"} user.add_resource(UserProfileResource, "/") app.register_blueprint(user_bp)

  3 、装饰器

    使用 method_decorators 添加装饰器

    ●为类视图中的所有方法添加装饰器

def decorator1(func):
def wrapper(*args, **kwargs):
print("decorator1")
return func(*args, **kwargs)
return wrapper def decorator2(func):
def wrapper(*args, **kwargs):
print("decorator2")
return func(*args, **kwargs)
return wrapper class DemoResource(Resource):
method_decorators = [decorator1, decorator2]

def get(self):
return {"msg": "get view"}

def post(self):
return {"msg": 'post view'}

    ●为类视图中不同的方法添加不同的装饰器

class DemoResource(Resource):
method_decorators = {
"get": [decorator1, decorator2],
"post": [decorator1]
}
# 使用了decorator1 decorator2两个装饰器
def get(self):
return {"msg": "get view"} # 使用也decorator1 装饰器
def post(self):
return {'msg': 'post view'} # 未使用装饰器
def put(self):
return {'msg': 'put view'}

三、关于请求处理

  Flask-RESTful 提供了 requestParser 类,用来帮助我们检验和转换请求数据。

from flask_restful import reqparse

parser = reqparse.RequestParser()
parser.add_argument('rate', type=int, help='Rate cannot be converted', location='args')
parser.add_argument("name")
args = parser.parse_args()

  1、使用步骤

    ① 创建 RequestParser 对象

    ② 向 RequestParser 对象中添加需要检验或转换的参数声明

    ③ 使用 parse_args() 方法启动检验处理

    ④ 检验之后从检验结果中获取参数时可按照字典操作或对象属性操作 

args.rate

args['rate']

  2、参数说明

    ① required

      描述请求是否一定要携带对应参数,默认值为False

      ●True 强烈要求携带,若未携带,则校验失败,向客户端返回错误信息,状态码400

      ●False 不强制要求携带,若不强烈携带,在客户端请求未携带参数时,取出值为 None

class DemoResource(Resource):
def get(self):
rp = RequestParser()
rp.add_argument('a', required=False)
args = rp.parse_args()
return {'msg': 'data={}'.format(args.a)}

  3、help

    参数检验错误时返回的错误描述信息

rp.add_argument('a', required=True, help="missing a param")

  4、action

    描述对于请求参数中出现多个同名参数时的处理方式

      ● action='store'  保留出现的第一个,默认

      ● action="append"  以列表追加保存所有同名参数的值

rp.add_argumen('a', required=True, help="missing a param", action='append')

  5、type

    描述参数应该匹配的类型,可以使用 python 的标准数据类型 string、int,也可使用Flask-RESTFul提供的检验方式,还可以自己定义

    ●标准类型

rp.add_argument('a', type=int, required=True, help="missing a param", action="append")

    ● Flask-RESTFul提供

    检验类型方法在 flask_restful.inputs 模块中

      ○ url

      ○ regex(指定正则表达式)

from flask_restful import inputs
rp.add_argument('a', type=inputs.regex(r'^\d{2}&'))

      ○ natural 自然数 0、1、2、3......

      ○ positive 正整数 1、2、3.....

      ○ int_range(low, high) 整数范围

rp.add_argument("a", type=inputs.int_range(1, 10))

      ○ boolean

    ● 自定义

def mobile(mobile_str):
"""
检验手机号格式
:param mobile_str: str 被检验字符串
:return: mobile_str
"""
if re.match(r'^1[3-9]\d{9}$', mobile_str):
return mobile_str
else:
raise ValueError('{} is not a vaild mobile'.format(mobile_str)) rp.add_argument('a', type=mobile)

  6、location

    描述参数应该在请求数据中出现的位置

# 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", location="headers") # From http cookies
parser.add_argument("session_id", location="cookies") # From json
parser.add_argument("user_id", location="json") # From file uploads
parser.add_argument("picture", location="file")

    也可指明多个位置

parser.add_argument("text", location=["headers", "json"])

四、关于响应处理

  1、序列化数据

    Flask-RESTful 提供了 marshal 工具,用来帮助我们将数据序列化特定格式的字典数据,以便作为视图的返回值。

from flask_restful import Resource, fields, marshal_with

resource_fields = {
"name": fields.String,
"address": fields.String,
"user_id": fields.Integer
} class Todo(Resource):
@marshal_with(resource_fields, envelope='resource')
def get(self, **kwargs):
return db_get_todo()

    也可以不使用装饰器的方式

class Todo(Resource):
def get(self, **kwargs):
data = db_get_todo()
return marshal(data, resource_fields)

示例

flask-基础篇03 RESTful的更多相关文章

  1. iOS系列 基础篇 03 探究应用生命周期

    iOS系列 基础篇 03 探究应用生命周期 目录: 1. 非运行状态 - 应用启动场景 2. 点击Home键 - 应用退出场景 3. 挂起重新运行场景 4. 内存清除 - 应用终止场景 5. 结尾 本 ...

  2. Java多线程系列--“基础篇”03之 Thread中start()和run()的区别

    概要 Thread类包含start()和run()方法,它们的区别是什么?本章将对此作出解答.本章内容包括:start() 和 run()的区别说明start() 和 run()的区别示例start( ...

  3. WebBug靶场基础篇 — 03

    基础篇 6 - 16 关... 在记录之前,先说一件事 = =! 小学生真多 = =!好心提供一个靶场,玩玩就算了,他挂黑页 ?现在好了,以后这个靶场不对外啊!你高兴了?爽了吧? 都是新手过来的,好心 ...

  4. 第一篇 Flask基础篇之(配置文件,路由系统,模板,请求响应,session&cookie)

    Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后 ...

  5. 第二篇 Flask基础篇之(闪现,蓝图,请求扩展,中间件)

    本篇主要内容: 闪现 请求扩展 中间件 蓝图 写装饰器,常用 functools模块,帮助设置函数的元信息 import functools def wrapper(func): @functools ...

  6. Java基础篇(03):流程控制语句,和算法应用

    本文源码:GitHub·点这里 || GitEE·点这里 一.分支语句 流程控制语句对任何一门编程语言都是非常重要的,Java中基于流程控制程序执行的不同步骤和代码块. 1.IF条件 IF条件语句会根 ...

  7. python框架之Flask基础篇(一)

    一.第一个hello world程序 # coding=utf-8 from flask import Flask app = Flask(__name__) @app.route('/') def ...

  8. python框架之Flask基础篇(四)-------- 其他操作

    1.蓝图 要用蓝图管理项目,需要导入的包是:from flask import Buleprint 具体大致分为三步: 1.先在子模块中导入蓝图包,然后再创建蓝图对象. 2.然后将子模块中的视图函数存 ...

  9. python框架之Flask基础篇(三)-------- 模版的操作

    1.flask特有的变量和函数: 变量:g.session.request.config 函数:url_for().get_flashed_messages()这个函数注意了啊,记住这是个函数,别忘了 ...

  10. python框架之Flask基础篇(二)-------- 数据库的操作

    1.flask连接数据库的四步: 倒入第三方数据库扩展包:from flask_sqlalchemy import SQLAlchemy 配置config属性,连接数据库: app.config[&q ...

随机推荐

  1. 迁移学习(ADDA)《Adversarial Discriminative Domain Adaptation》

    论文信息 论文标题:Adversarial Discriminative Domain Adaptation论文作者:Eric Tzeng, Judy Hoffman, Kate Saenko, Tr ...

  2. HOMER docker版本安装详细流程

    概述 HOMER是一款100%开源的针对SIP/VOIP/RTC的抓包工具和监控工具. HOMER是一款强大的.运营商级.可扩展的数据包和事件捕获系统,是基于HEP/EEP协议的VoIP/RTC监控应 ...

  3. 高效字符串匹配算法——BM 算法详解(C++)

    定义 BM 算法是由 Boyer 和 Moore 两人提出的一种高效的字符串匹配算法,被认为是一种亚线性算法(即平均的时间复杂度低于线性级别),其时间效率在一般情况下甚至比 KMP 还要快 3 ~ 5 ...

  4. jsp传入servlet数据

    面对老师的19级期末,要用到jsp传入servlet的数据传输,借鉴了其他人的代码,以下是我的程序 jsp界面: <%request.getSession().setAttribute(&quo ...

  5. Trie 的一类应用

    \(\text{Trie}\) 先从 [十二省联考 \(2019\)] 异或粽子 谈起 不难想到堆加可持久化 \(Trie\) 的做法 这就和 \(\text{[NOI2010]}\) 超级钢琴 类似 ...

  6. 免杀之:Python加载shellcode免杀

    免杀之:Python加载shellcode免杀 目录 免杀之:Python加载shellcode免杀 1 Python 加载Shellcode免杀 使用Python可以做一些加密.混淆,但使用Pyth ...

  7. Vulhub 漏洞学习之:Django

    Vulhub 漏洞学习之:Django 目录 Vulhub 漏洞学习之:Django 1 Django debug page XSS漏洞(CVE-2017-12794) 1.1 漏洞利用过程 2 Dj ...

  8. 普冉PY32系列(六) 通过I2C接口驱动PCF8574扩展的1602LCD

    目录 普冉PY32系列(一) PY32F0系列32位Cortex M0+ MCU简介 普冉PY32系列(二) Ubuntu GCC Toolchain和VSCode开发环境 普冉PY32系列(三) P ...

  9. c++多线程thread用法小例子

    测试分布式存储系统时,针对并发测试,同时创建500个文件,采用这种方法. #include<iostream> #include<thread> using namespace ...

  10. Create 1select+jdbc+jsp

    <form action="UserServlet" method="get"> 查询条件:<input type="text&qu ...