完成登录功能,用session记住用户名
from flask import Flask, render_template,request,redirect,url_for,session from flask_sqlalchemy import SQLAlchemy # import config from functools import wraps from datetime import datetime app = Flask(__name__) db = SQLAlchemy(app) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(20), nullable=False) password = db.Column(db.String(20), nullable=False) nickname = db.Column(db.String(20)) @app.route('/') def index(): return render_template('test.html') @app.route('/login',methods=['GET','POST']) def login(): if request.method == 'GET': return render_template('test.html') else: username = request.form.get('username') password = request.form.get('password') nickname = request.form.get('nickname') user = User.query.filter(User.username == username).first() if user: return '用户名已存在' else: user = User(username=username, password=password) db.session.add(user) db.session.commit() return render_template(url_for('login')) @app.route('/regist',methods=['GET','POST']) def regist(): if request.method == 'GET': return render_template('注册.html') else: username = request.form.get('username') password = request.form.get('password') nickname = request.form.get('nickname') user = User.query.filter(User.username == username).first() if user: return '用户名存在' else: user = User(username = username,password = password,nickname=nickname) db.session.add(user) db.session.commit() return render_template(url_for('login')) @app.route('/fabu') def fabu(): return render_template('fabu.html') if __name__ == '__main__': app.run(debug=True)