一、起步:

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. 高并发环境下3种方式优化Tomcat性能

    摘要:Tomcat作为最常用的Java Web服务器,随着并发量越来越高,Tomcat的性能会急剧下降,那有没有什么方法来优化Tomcat在高并发环境下的性能呢? 本文分享自华为云社区<[高并发 ...

  2. 单细胞转录组实战01: CellRanger7定量

    安装CellRanger cd ~/APP wget -O cellranger-7.1.0.tar.xz "https://cf.10xgenomics.com/releases/cell ...

  3. Kubernetes(k8s)控制器(一):deployment

    目录 一.系统环境 二.前言 三.Kubernetes 控制器 四.Deployment概览 五.创建deployment 六.修改deploy副本数 6.1 kubectl edit deploy ...

  4. 平台工程101:Dev、Sec和Ops的自动化黏合剂

    国际权威知名调研机构 Gartner 在<2023年最重要的10个技术趋势>报告中将平台工程(Platform Engineering)列为高速发展的技术趋势之一,并预测到2026年80% ...

  5. 火山引擎 DataLeap:3 个关键步骤,复制字节跳动一站式数据治理经验

    更多技术交流.求职机会,欢迎关注字节跳动数据平台微信公众号,并进入官方交流群 DataLeap 是火山引擎数智平台 VeDI 旗下的大数据研发治理套件产品,帮助用户快速完成数据集成.开发.运维.治理. ...

  6. 《自定义工作流配置,springboot集成activiti,前端vue,完整版审批单据》

    前言 activiti工作流引擎项目,企业erp.oa.hr.crm等企事业办公系统轻松落地,一套完整并且实际运用在多套项目中的案例,满足日常业务流程审批需求. 一.项目形式 springboot+v ...

  7. Kubernetes环境cert-manager部署与应用

    本作品由Galen Suen采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可.由原作者转载自个人站点. 概述 本文用于整理基于Kubernetes环境的cert-manager部 ...

  8. Mybatis的逆向工程与延迟加载

    Mybatis 的逆向工程 Mybatis是一个半自动化的ORM框架,SQL语句需要要开发者自己定义,SQL定义在Mapper.xml中,与对应的Mapper接口对应 实体类 接口 Mapper.xm ...

  9. clicknium-划时代的自动化

    说起UI自动化,selenium一直是不可替代的存在,它的安装量.百度数量已经奠定了它在自动化.爬虫等相关领域的霸主低位,可以说,只要涉及到UI自动化,选selenium就对了. 细数过往,相关的UI ...

  10. JZOJ 2022.07.06【提高组A】模拟

    历程 被暴打了 原因是钻进了 \(T4\) 的坑中... 先看完题,发现 \(T4\) 比较有意思,\(T2\) 没有想法 \(T3\) 挺容易,做法似乎很好想 \(T1\) 送分,十几分钟搞定 然后 ...