当前位置:网站首页>Flask框架——基于类的视图
Flask框架——基于类的视图
2022-08-07 09:47:00 【白巧克力LIN】
目录
在上篇文章学习了Flask框架——项目可安装化,这篇文章我们学习Flask框架——基于类的视图。
基于类的视图有两种:继承View的类视图和继承MethodView的类视图。
基于类的视图是以类的方式实现视图函数的逻辑,封装视图函数,能够比较优雅的方式实现很多复杂的不同功能。
例如:类的方法视图函数封装了处理get、post请求的函数,当请求方法为get就调用类中的get请求函数,当请求方法为post请求时,就调用类中的post请求函数。
这样根据请求方法来和类中的函数形成一个绑定关系,从而达到映射的效果。
基于类的视图好处:
类是可以继承的,我们可以编写一个基础的类视图来继承特定功能的类视图,实现代码复用;
可以定义多种函数实现多个功能,逻辑清晰。
例如:Flask程序使用传统的视图函数,示例代码如下:
from flask import Flask, request
app=Flask(__name__)
@app.route("/index/<index_id>", methods=["GET", "POST", "PUT", "DELETE"])
def index(index_id):
method = request.method
if method == "GET":
if user_id is None:
.....
return f"get {index_id}"
elif method == "post":
.....
return f"post {index_id}"
elif method=='PUT':
.....
return '......'
....
return "其他的方法判断"
if __name__ == '__main__':
app.run(debug=True)
在传统的视图函数中,我们通常会在视图函数中添加很多if判断来满足不同的请求类型,如果判断的代码有很多,那么在一个视图函数中就显得很臃肿,不利于我们后期进行维护。
这时我们可以使用基于类的视图函数——继承View的类视图。
继承View的类视图
Flask示例代码如下:
from flask.views import View
from flask import Flask, request
class index(View): #创建index类继承View
methods = ["GET", "POST"] #该类接收的请求类型
def get(self): #get请求
return "get"
def post(self): #post请求
return "post"
def dispatch_request(self): #重写dispatch_request方法
request_method = {"get": self.get, "post": self.post} #请求类型和请求方法绑定
view = request_method.get(request.method.lower()) #通过请求方法,映射到对应的函数对象
return view() #返回view值
app = Flask(__name__)
app.add_url_rule("/index", view_func=index.as_view("index")) #注册视图函数
if __name__ == '__main__':
app.run(debug=True)
首先我们创建名为index的类,添加请求类型并为每种请求类型添加函数,重写dispatch_request()方法来为请求类型和请求方法进行绑定,这样当我们接收不同类型的请求就可以调用对应的请求方法,最后通过app.add_url_rule()方法来注册视图函数,其中第一个参数为URL,第二个参数是视图函数名,需要使用as_view()方法把类转换为实际的视图函数,上面的视图函数名为index。
注意:
基于类的视图函数要基础View;
必须重写dispatch_request方法,主要实现请求调度的作用;
请求类型可以放在类的methods属性里面;
基于类的视图不能用@app.route装饰器来注册路由,只能用add_url_rule方法绑定视图。
继承View的类视图核心是基于dispatch_request方法调度的。
继承MethodView的类视图
对比传统的视图函数和继承View的类视图,继承View的类视图虽然逻辑比较清晰了,但代码更多了,这主要是继承View的类视图需要重写dispatch_request()方法,这时我们可以使用继承MethodView的类视图,它里面帮我们用获取类属性的方式重写了dispatch_request方法,这样我们就不需要再重写dispatch_request方法。
Flask程序示例代码如下:
from flask.views import MethodView
from flask import Flask
class index(MethodView): #创建index类并继承MethodView类
def get(self): #get请求
return "get"
def post(self): #post请求
return "post"
app = Flask(__name__)
app.add_url_rule("/index", view_func=index.as_view("index")) #注册视图函数
if __name__ == '__main__':
app.run(debug=True)
对比传统视图函数、继承View的类视图和继承MethodView的类视图,明显继承MethodView的类视图结构和逻辑更清晰。
那么怎么满足不同的请求类型呢?
假如我有个名为total类,该类继承了MethodView类,如下所示:
class total(MethodView): #创建total类并继承MethodView类
def get(self): #get请求
return "get"
def post(self): #post请求
return "post"
def put(self): #put请求
return "put"
def delete(self): #delete请求
return "delete"
该类可以处理不同的请求类,如get、post、put和delete请求,那么怎样实现不同的url请求类型返回对应的请求函数呢。方法很简单,如下所示:
view_func = total.as_view("total")
app.add_url_rule("/projects", view_func=view_func, methods=["GET"])
app.add_url_rule("/project/create", view_func=view_func, methods=["POST"])
只要在使用add_url_rule绑定视图时,添加methods参数即可。
好了,Flask框架——基于类的视图就讲到这里了,感谢观看,下篇文章学习Flask框架——应用错误处理!!
公众号:白巧克力LIN
该公众号发布Python、数据库、Linux、Flask、自动化测试、Git等相关文章!
- END -
边栏推荐
- 【图像分类】2022-RepLKNet CVPR 31x31卷积了解一下
- Node的知识理解
- The principle and source code of redis-sentinel sentinel principle and source code analysis (on)
- TikTok视频播放量低,是被限流了吗?
- 你如何看待抖音的中视频伙伴计划的?
- Selection sort (simple selection sort and heap sort)
- Unity 3D 游戏通用系统设置页面,自定义按键设置,背景虚化,图像设置,亮度对比度饱和度音量调节,分辨率窗口化,帧率垂直同步,抗锯齿,阴影质量,纹理质量设置
- In-depth analysis of Spark SQL illustrates the execution process and application scenarios of five Join strategies
- 【Go】(1)go语言开发环境配置
- Addition, deletion, search and modification of doubly linked list
猜你喜欢

The principle and source code of redis - the principle and source code analysis of cluster (on)

1324_FreeRTOS queue creation function implementation analysis

Excel export operation based on ABP and Magiccodes

360企业安全云亮相2022全球数字经济大会 夯实中小微企业数字化底座

Unity 3D 游戏通用系统设置页面,自定义按键设置,背景虚化,图像设置,亮度对比度饱和度音量调节,分辨率窗口化,帧率垂直同步,抗锯齿,阴影质量,纹理质量设置

Principle of redis and source - redis data types of coding formats and data structures, a list, dict, SDS zskiplist, intset, ziplist, quicklist, listpack, rax, stream

The principle and source code of redis-redis memory elimination strategy & LRU source code analysis & LFU source code analysis

The principle and source code of redis - transaction mechanism

Unity 3D game general system settings page, custom key settings, background blur, image settings, brightness, contrast, saturation, volume adjustment, resolution windowing, frame rate vertical sync, a

4.2 实现注册与登录模块
随机推荐
SkiaSharp 之 WPF 自绘 投篮小游戏(案例版)
How does Apache, the world's largest open source foundation, work?
中国手机持续创新,全面屏再进一步,引领手机创新
The principle and source code of redis - introduction of client structure and source code analysis
Node的知识理解
LVS+Keepalived高可用群集部署
LeetCode [206. Reverse linked list] (1)
2022 Niuxue Multi-School League Game 6 Solution
In-depth analysis of Spark SQL illustrates the execution process and application scenarios of five Join strategies
Automatic processing software for geometric data topology errors based on FME
Redis principle and way of source data persistence RDB introduction and source code parsing
为了高性能、超大规模的模型训练,这个组合“出道”了
为什么我要说:柯里化 == 闭包+递归?
China's mobile phones continue to innovate, and the full screen goes further, leading mobile phone innovation
redis的原理和源码-事件机制的介绍和源码解析(eventloop、fileevent、timeevent)
VPC5021电流模式 PWM 控制器 3uA 超低启动电流
双向链表的增删查改
Possible errors when using scanf()
2022牛客多校联赛第六场 题解
[Punctuality Atom STM32 Serial] Chapter 6 New Register Version MDK Project Excerpted from [Punctual Atom] MiniPro STM32H750 Development Guide_V1.1