from flask import views from flask import Flask from flask import render_template from flask import request, url_for from flask import make_response from flask import redirect from functools import wraps app = Flask(__name__, template_folder='../templates') # 函数视图 # @app.route('/') # def login(): # return render_template('test.html') # 标准类视图是继承自flask.views.View,并且在子类中必须实现dispatch_request方法 # 这个方法类似于视图函数,也要返回一个基于Response或者其子类的对象,默认请求为get请求。 class Model(object): def __init__(self, username, password): self.username = username self.password = password # 登入装饰器 def login_required(func): @wraps(func) def decorate(*args, **kwargs): username = request.cookies.get('username') if username: return func(*args, **kwargs) else: return '请先登入哦!' return decorate class RegisterView(views.View): methods = ['GET', 'POST'] def dispatch_request(self): global user_03 if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') user_03 = Model(username, password) return render_template('test.html') class LoginView(views.View): methods = ['GET', 'POST'] def dispatch_request(self): if request.method == 'GET': return render_template('login.html') username = request.form.get('username') password = request.form.get('password') if username and password: if user_03.username == username and user_03.password == password: response = make_response(redirect(url_for('index'))) response.set_cookie('username', username) return response else: return '用户名或密码错误!' class IndexView(views.View): decorators = [login_required] def dispatch_request(self): return render_template('index.html') app.add_url_rule('/register', view_func=RegisterView.as_view('register')) app.add_url_rule('/login', view_func=LoginView.as_view('login')) app.add_url_rule('/index', view_func=IndexView.as_view('index')) if __name__ == '__main__': app.run()