flask代码——装饰器与CBV
装饰器
# -*- coding:utf-8 -*- from flask import Flask,request,render_template,jsonify,redirect,send_file,Markup app = Flask(__name__) app.config['DEBUG'] = True @app.before_request def f1(): print('before request...') return None @app.after_request def f2(response): print('after request...') return response @app.after_request def f3(response): print('f3...') return response # 自定制错误响应 @app.errorhandler(404) def err0r404(error_msg): print(error_msg) # 这个文件位于当前py文件同一个目录下 return send_file('error_404.jpeg') @app.route('/',methods=['GET','POST']) def index(): dic = { 'msg':'你好' } return render_template('index.html',dic=dic) @app.route('/login',methods=['GET','POST']) def login(): if request.method == 'GET': return render_template('login.html') elif request.method == 'POST': print(request.form) print(request.form.get('password')) return '666' if __name__ == '__main__': app.run('127.0.0.1',9001)
对应的登陆页面
<!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>
Flask的CBV写法
# -*- 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) # 这个文件位于当前py文件同一个目录下 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方法来调用! app.add_url_rule('/',view_func=LoginView.as_view(name='login'),endpoint='login') if __name__ == '__main__': app.run('127.0.0.1',9011)
~~~