- 类视图的应用背景:之前我们接触的视图都是函数,所以一般简称视图函数,函数视图的问题在于,每个新的页面要一个路由函数,比较复杂。其实视图也可以基于类来实现,类视图的好处是支持继承,但是类视图不能跟函数视图一样,写完类视图还需要通过app.add_url_rule(url_rule,view_func)来进行注册。
- 类测试 可以返回json类型的数据
- 标准类视图:标准类视图是继承自flask.views.View,并且在子类中必须实现dispatch_request方法,这个方法类似于视图函数,也要返回一个基于Response或者其子类的对象
类似图示例:
class ListView(views.View):
def dispatch_request(self):
return '这是类测试的测试'
“实例化”类视图
app.add_url_rule('/list/',view_func=ListView.as_view('list')) #as_view 为类起别名
# endpint 的作用 和as_view的作用是一样的,都是起别名的作用
# 当两者都存在的时候,endpoint起作用 listjson不再起作用
同样的,
定义函数视图:
def profile():
return '个人中心'
也可以通过该方式调用:
app.add_url_rule('/profile/',view_func=profile)
定义类视图的方式 继承views.View
完整代码:
from flask import Flask,views,jsonify,url_for
app = Flask(__name__)
@app.route('/')
def index():
print(url_for('listjson1'))
return '首页'
#@app.route('/profile/')
def profile():
return '个人中心'
class ListView(views.View):
def dispatch_request(self):
return '这是类测试的测试'
# def demo(self):
# return '这是测试'
class JsonView(views.View):
def get_response(self):
raise NotImplementedError()
def dispatch_request(self):
response = self.get_response()
return jsonify(response)
class ListJsonView(JsonView):
def get_response(self):
return {'username':'cheney'}
app.add_url_rule('/profile/',view_func=profile)
app.add_url_rule('/list/',view_func=ListView.as_view('list')) #as_view 为类起别名
app.add_url_rule('/listjson/',endpoint = 'listjson1',view_func=ListJsonView.as_view('listjson'))
# endpint 的作用 和as_view的作用是一样的,都是起别名的作用
# 当两者都存在的时候,endpoint起作用 listjson不再起作用
if __name__ == '__main__':
app.run(debug=True,port=8888)
标准类视图:
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<p> {{ username }} </p>
</body>
</html>
regist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>注册</h1>
<p> {{ username }} </p>
</body>
</html>
python 文件
#! C:\Python\Python36
# -*- coding: utf-8 -*-
# @Time : 2020/10/23 19:01
# @Author : liuchengyong
# @File : view_use.py
# @Software: PyCharm
from flask import Flask,views,jsonify,url_for,render_template
app = Flask(__name__)
@app.route('/')
def index():
return '首页'
class BaseView(views.View):
def __init__(self):
self.context = {
'username': 'cheney'
}
class LoginView(BaseView):
def dispatch_request(self):
self.context = {
'username':'cheney'
}
return render_template('login.html',**self.context)
class RegistView(BaseView):
def dispatch_request(self):
self.context = {
'username': 'cheney'
}
return render_template('regist.html',**self.context)
app.add_url_rule('/login/',view_func=LoginView.as_view('login'))
app.add_url_rule('/regist/',view_func=RegistView.as_view('regist'))
if __name__ == '__main__':
app.run(debug=True,port=8008)
通过以上的文件,可以实现一个通过python文件传递参数到标准类视图中的程序。
加油,远离负能量场,用正能量面对生活