flask的类视图
#_*_ encoding: utf-8 _*_ @author: ty hery 2020/4/6
from flask.views import View
from flask import Flask, render_template, request,views,jsonify
app = Flask(__name__)
class PersonalView(View):
def dispatch_request(self):
return "知了课堂"
# 类视图通过add_url_rule方法和url做映射
app.add_url_rule('/users/',view_func=PersonalView.as_view('personalview'))
class LoginView(views.MethodView):
# 当客户端通过get方法进行访问的时候执行的函数
def get(self):
return render_template("login.html")
# 当客户端通过post方法进行访问的时候执行的函数
def post(self):
email = request.form.get("email")
password = request.form.get("password")
if email == '123@qq.com' and password == '111111':
return "登录成功!"
else:
return "用户名或密码错误!"
# 通过add_url_rule添加类视图和url的映射,并且在as_view方法中指定该url的名称,方便url_for函数调用
app.add_url_rule('/myuser/',view_func=LoginView.as_view('loginview'))
#_*_ encoding: utf-8 _*_ @author: ty hery 2020/4/6
class Listview(views.View):
def dispatch_request(self):
return 'list view'
class JsonView(views.View):
def get_data(self):
raise NotImplementedError
def dispatch_request(self):
return jsonify(self.get_data())
class ListView(JsonView):
def get_data(self):
return {'username':'zhiliao','password':'111111'}
app.add_url_rule('/list/',endpoint='list',view_func=ListView.as_view('list')) # 先去执行ListView里面的dispatch_request方法,没有执行他父辈的,他父辈执行ListView里面的get_data方法获取数据
if __name__ == '__main__':
app.run('0.0.0.0',8888,debug=True)
# app.run('0.0.0.0',port=8888,debug=True)
templates/login.html
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
{# <link rel="stylesheet" href="/sss/commons.css"/>#}
</head>
<body>
<h1>Hello Login 哈哈哈</h1>
<form method="POST" >
email: <input type="text" name="email" placeholder="邮件地址"/></br>
password: <input type="password" name="password" placeholder="密码"/></br>
<input type="submit" value="提交" />
</form>
</body>
<footer>
</footer>
</html>
写入自己的博客中才能记得长久