当前位置:网站首页>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')
边栏推荐
猜你喜欢
随机推荐
B1026 程序运行时间
redis发布订阅模式
Notes Series docker installation PostgreSQL 14
Critical path principle
34. Analyze flexible.js
JVM Part 1: memory and garbage collection part 12 -- stringtable
Rolling Division
268.missing number of leetcode
LeetCode刷题之322 Coin Change
Create datasource using Druid connection pool
B1029 old keyboard
Pinball games
How to quickly and effectively solve the problem of database connection failure
2022 Zhengzhou light industry Freshmen's competition topic - I won't say if I'm killed
JVM Part 1: memory and garbage collection part 11 -- execution engine
[optical flow] - data format analysis, flowwarp visualization
B1021 single digit statistics
How to view the evaluation of tutors
消息可靠性处理
Raspberry pie RTMP streaming local camera image





![[CSAPP] Application of bit vectors | encoding and byte ordering](/img/96/344936abad90ea156533ff49e74f59.gif)



