from flask import Flask app = Flask(__name__) @app.route(‘/‘) def index(): return ‘hello world‘ app.run(debug = True)
Flask.views.View 是 Flask 的标准视图类,用户定义的视图类需要继承于 Flask.views.View 。使用视图类的步骤如下:
#!usr/bin/env python # -*- coding:utf-8 _*- """ # author: 小菠萝测试笔记 # blog: https://www.cnblogs.com/poloyy/ # time: 2021/7/13 8:42 下午 # file: 8_view_class.py """ from flask import Flask, views from flask.typing import ResponseReturnValue app = Flask(__name__) # 自定义视图类,继承 views.View class view_test(views.View): # 返回一个字符串给客户端 def dispatch_request(self) -> ResponseReturnValue: return "hello world" # 将路由规则 / 和视图类 view_test 进行绑定 app.add_url_rule(rule="/", view_func=view_test.as_view("view")) if __name__ == ‘__main__‘: app.run()
视图类的本质是视图函数,函数 View.as_view () 会返回一个视图函数
为了更清晰理解 as_view 函数的功能,自行实现一个简化版本的 as_view 函数
#!usr/bin/env python # -*- coding:utf-8 _*- """ # author: 小菠萝测试笔记 # blog: https://www.cnblogs.com/poloyy/ # time: 2021/7/13 8:42 下午 # file: 8_view_class.py """ from flask import Flask, views from flask.typing import ResponseReturnValue app = Flask(__name__) class view_test2(views.View): def dispatch_request(self) -> ResponseReturnValue: return {"msg": "success", "code": 0} @staticmethod def as_view(name, **kwargs): view = view_test2() return view.dispatch_request # 将路由规则 / 和视图类 view_test 进行绑定 app.add_url_rule(rule="/", view_func=view_test2.as_view("view")) if __name__ == ‘__main__‘: app.run()
使用类视图的好处是支持继承,可以把一些共性的东西放在父类中,其他子类可以继承
#!usr/bin/env python # -*- coding:utf-8 _*- """ # author: 小菠萝测试笔记 # blog: https://www.cnblogs.com/poloyy/ # time: 2021/7/13 10:15 下午 # file: s8_baseview.py """ from flask import Flask, views, render_template app = Flask(__name__) class BaseView(views.View): # 如果子类忘记定义 get_template 就会报错 def get_template(self): raise NotImplementedError() # 如果子类忘记定义 get_data 就会报错 def get_data(self): raise NotImplementedError() def dispatch_request(self): # 获取模板需要的数据 data = self.get_data() # 获取模板文件路径 template = self.get_template() # 渲染模板文件 return render_template(template, **data)
#!usr/bin/env python # -*- coding:utf-8 _*- """ # author: 小菠萝测试笔记 # blog: https://www.cnblogs.com/poloyy/ # time: 2021/7/13 10:15 下午 # file: 8_userview.py """ from s8_baseview import BaseView class UserView(BaseView): def get_template(self): return "user.html" def get_data(self): return { ‘name‘: ‘zhangsan‘, ‘gender‘: ‘male‘, }
#!usr/bin/env python # -*- coding:utf-8 _*- """ # author: 小菠萝测试笔记 # blog: https://www.cnblogs.com/poloyy/ # time: 2021/7/13 10:31 下午 # file: 8_app.py """ from flask import Flask, views from s8_userview import UserView app = Flask(__name__) app.add_url_rule(‘/user/‘, view_func=UserView.as_view(‘UserView‘)) app.run(debug=True)
<html> <body> <h2>name = {{ name }}</h2> <h2>gender = {{ gender }}</h2> </body> </html>
在视图函数、视图类中使用装饰器还是一大杀器
不使用装饰器前的代码
def check_login(): if 用户已经登录: return True else: return False @app.route(‘/page1‘, page1) def page1(): if not check_login(): return ‘请先登录‘ 执行 page1 的功能 @app.route(‘/page2‘, page2) def page2(): if not check_login(): return ‘请先登录‘ 执行 page2 的功能
使用装饰器实现登录的功能,定义检查登录的装饰器 check_login
from flask import request from functools import wraps def check_login(original_function): @wraps(original_function) def decorated_function(*args, **kwargs): user = request.args.get("user") if user and user == "zhangsan": return original_function(*args, **kwargs) else: return "请登录" return decorated_function()
#!usr/bin/env python # -*- coding:utf-8 _*- """ # author: 小菠萝测试笔记 # blog: https://www.cnblogs.com/poloyy/ # time: 2021/7/13 10:31 下午 # file: 8_app.py """ from flask import Flask, request from functools import wraps app = Flask(__name__) # 定义装饰器 def check_login(original_function): @wraps(original_function) def decorated_function(*args, **kwargs): user = request.args.get("user") if user and user == "zhangsan": return original_function(*args, **kwargs) else: return "请登录" return decorated_function() @app.route("/page1") @check_login def page1(): return "page1" @app.route("/page2") @check_login def page2(): return "page2" app.run(debug=True)
#!usr/bin/env python # -*- coding:utf-8 _*- """ # author: 小菠萝测试笔记 # blog: https://www.cnblogs.com/poloyy/ # time: 2021/7/13 11:06 下午 # file: 8_viewclass_decorated.py """ from flask import Flask, request, views from functools import wraps app = Flask(__name__) def check_login(original_function): @wraps(original_function) def decorated_function(*args, **kwargs): user = request.args.get("user") if user and user == ‘zhangsan‘: return original_function(*args, **kwargs) else: return ‘请先登录‘ return decorated_function class Page1(views.View): decorators = [check_login] def dispatch_request(self): return ‘Page1‘ class Page2(views.View): decorators = [check_login] def dispatch_request(self): return ‘Page2‘ app.add_url_rule(rule=‘/page1‘, view_func=Page1.as_view(‘Page1‘)) app.add_url_rule(rule=‘/page2‘, view_func=Page2.as_view(‘Page2‘)) app.run(debug=True)
decorators = [check_login] 设定视图类的装饰器
原文:https://www.cnblogs.com/poloyy/p/15008909.html