flask基础3——CBV实现登陆的实例
CBV的使用
后台的写法1——普通的用法:
# -*- coding:utf-8 -*- from flask import Flask, views, render_template, request app = Flask(__name__) app.debug = True @app.route('/index') def index(): return 'index' class Login(views.MethodView): # 这样写的话就只支持get方法了~~ # methods = ['GET'] def get(self): return render_template('login.html') def post(self): uname = request.form.get('username') pwd = request.form.get('password') if uname == 'whw' and pwd == '123': return '登陆成功' else: return '登陆失败' # 必须用add_url_rule方法来调用! # as_view必须有一个name参数! app.add_url_rule('/login',endpoint='login',view_func=Login.as_view(name='login')) if __name__ == '__main__': app.run()
后台的写法2——有打散传参的方式:
# -*- coding:utf-8 -*- from flask import views,Flask,request,render_template,send_file app = Flask(__name__) app.debug = True # 自定制错误响应 @app.errorhandler(404) def err0r404(error_msg): print(error_msg) return send_file('error_404.jpeg') class LoginView(views.MethodView): def get(self): return render_template('login.html') def post(self): uname = request.form.get('username') pwd = request.form.get('password') print(uname,'>>>',pwd) if uname == 'whw' and pwd == '123': # msg = '登陆成功!' # msg_class = 'green' # return render_template('login.html',msg=msg,msg_class=msg_class) dic = {'msg':'登陆成功', 'msg_class':'green' } return render_template('login.html',**dic) else: msg = '登陆失败!' msg_class = 'red' return render_template('login.html',msg=msg,msg_class=msg_class) # # 必须用add_url_rule方法来调用!
# as_view必须有一个name参数!
app.add_url_rule('/',view_func=LoginView.as_view(name='login'),endpoint='login') if __name__ == '__main__': app.run('127.0.0.1',9011)
login.html页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> <style> .red{ color:red; } .green{ color: green; } </style> </head> <body> <form action="" method="post"> 用户名: <input type="text" name="username" autocomplete="off"> 密码: <input type="password" name="password" autocomplete="off"> <input type="submit"> <span class="{{ msg_class }}">{{ msg }}</span> </form> </body> </html>