当前位置:网站首页>Day4 --- Flask 蓝图与Rest-ful
Day4 --- Flask 蓝图与Rest-ful
2022-07-27 05:02:00 【qishaoawei】
蓝图
蓝图的使用步骤分为三步:
1.创建一个蓝图对象
2.在这个蓝图对象上进行操作, 注册路由, 指定静态文件夹, 注册模板过滤器
3.在应用对象上注册蓝图对象
开始创建
蓝图的实现
创建一个app.py文件跟一个目录
app.py文件中编写
from flask import Flask
from views.user import user_bp #从蓝图文件里导入蓝图对象
# 创建Flask实例
app=Flask(__name__)
app.register_blueprint(user_bp) #注册蓝图
if __name__ == '__main__':
app.run()
在创建的views目录下创建user.py文件
类似于django中的子应用
# 1创建蓝图 & 2添加蓝图路由
from flask import Blueprint
# url_prefix # 指定当前蓝图下所有路由的前缀
user_bp=Blueprint('user_bp',__name__,url_prefix='/user')
# 添加蓝图路由
@user_bp.route('/hello')
def hello():
return 'hello'
返回响应
Flask-RESTful配合蓝图
在目录下的user.py文件中编写
from flask import Blueprint
# url_prefix # 指定当前蓝图下所有路由的前缀
user_bp=Blueprint('user_bp',__name__,url_prefix='/user')
# #初识Flask-RESTful
from flask_restful import Api,Resource #导入Api跟Resource类
#实例化一个Api对象 Api对象的作用是用来搜集路由的
api=Api(user_bp)
#定义一个类,继承自Resource类,通过Api的实例化对象进行搜集
class Users(Resource):
def get(self):
return 'hello2'
## Users是定义的类名, '/users'是自定义的路由
api.add_resource(Users,'/users')
返回响应
视图类的装饰器
装饰器的基本写法
可以为为单个方法指定装饰器
也可以都使用装饰器
#装饰器的基本写法
def dec1(func):
def warpper(*args,**kwargs):
#要写的装饰器内容
print('dec1')
return func(*args,**kwargs)
return warpper
class Users(Resource):
## 只允许get方法使用装饰器 第一种
method_decorators = {
'get':[dec1]}
### 只要是这个类被调用 就使用装饰器 第二种
## method_decorators = [dec1]
def get(self):
return 'hello2'
## Users是定义的类名, '/users'是自定义的路由
api.add_resource(Users,'/users')
边栏推荐
- JVM上篇:内存与垃圾回收篇--运行时数据区四-程序计数器
- 322 coin change of leetcode
- Differences among bio, NiO and AIO
- B1022 a+b in d-ary
- 268.missing number of leetcode
- Gradio quickly builds ml/dl Web Services
- 强制登录,七牛云上传图片
- 内部类与静态内部类区别及举例
- JDBC API details
- Explore the mysteries of the security, intelligence and performance of the universal altek platform!
猜你喜欢

JDBC API 详解

如何将Excel表格中的多列内容合并到一列

JVM上篇:内存与垃圾回收篇七--运行时数据区-堆

实用小工具: Kotlin 代码片段

Prime number screening (Ehrlich sieve method, interval sieve method, Euler sieve method)

JVM Part 1: memory and garbage collection part 3 - runtime data area - overview and threads

Scientific Computing Library - numpy

2021 OWASP top 5: security configuration error

Shell course summary

如何快速有效解决数据库连接失败问题
随机推荐
268.missing number of leetcode
数据库设计——关系数据理论(超详细)
B1030 perfect sequence
笔记系列之docker安装Postgresql 14
B1028 人口普查
LocalDateTime和ZonedDateTime
Integrate SSM
弹球小游戏
订单系统功能实现
Sparse array → saving and continuation of Gobang
内部类与静态内部类区别及举例
LeetCode刷题之322 Coin Change
接收方设置并发量和限流
JVM Part 1: memory and garbage collection part 7 -- runtime data area heap
创建项目 实现登录注册,生成jwt,发送验证码
Flask的使用
mq设置过期时间、优先级、死信队列、延迟队列
torch中乘法整理,*&torch.mul()&torch.mv()&torch.mm()&torch.dot()&@&torch.mutmal()
蓝图-类视图方法
JDBC API details