flask之CBV模式-LMLPHP

flask_cbv.py

 '''
flask中的CBV模式:
(1)导入views模块: from flask import views
(2)定义类,继承views.MethodView类: class 类名(views.MethodView)
(3)在类中定义函数名为允许的请求方式的小写形式,进行函数定义,如def get(self):...
(4)添加路由规则:
CBV:app.add_url_rule(rule,endpoint='',view_func=类名.as_view(name=''))
FBV:app.add_url_rule(rule,endpoint='',view_func=函数名))(直接替代@app.route()方式) 参数:
rule 请求路径
endpoint设置mapping路由映射函数rule:{endpoint:func}
view_func路由映射的视图函数或者类(as_view()中的name参数设置当前路由映射函数名,唯一指定,不设置endpoint自动为name值)
(5)methods=[]类中设置属性,添加允许的请求方式,不写默认都支持
(6)decorators = []对类中的函数都加上装饰器,列表中可以放多个装饰器函数名,以此执行 '''
from flask import Flask, views, render_template, send_file, request, session app=Flask(__name__)
app.secret_key='wertyui234567gf!@#$%^&*(' class Login(views.MethodView):
# methods = ['get', 'post', 'head', 'options','delete', 'put', 'trace', 'patch']#可以在类中指定允许的请求方式,不指定会根据定义的函数进行选择
decorators = []#对类中的函数都加上装饰器,列表中可以放多个装饰器函数名,以此执行
def get(self):
return render_template('login.html')
def post(self):
username=request.form.get('username')
pwd=request.form.get('pwd')
if username == 'yang' and pwd == '':
session['username'] = 'yang'
return '登录成功!'
else:
return '账号或密码有误!!!!'
#路由映射视图函数
app.add_url_rule('/login',view_func=Login.as_view(name='login')) if __name__ == '__main__':
app.run()

lohin.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>logine</title>
</head>
<body>
<form action="" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="pwd">
<input type="submit" value="提交">
</form>
</body>
</html>
05-26 06:50