from flask import Flask, render_template, url_for, redirect, request,session from flask_sqlalchemy import SQLAlchemy from functools import wraps import config from datetime import datetime app = Flask(__name__) app.config.from_object(config) 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)) class Question(db.Model): __tablename__ ='question' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(100),nullable=False) detail = db.Column(db.Text,nullable=False) creat_time = db.Column(db.DateTime,default=datetime.now) author_id = db.Column(db.Integer,db.ForeignKey('user.id')) author = db.relationship('User',backref=db.backref('question')) db.create_all() # 增加 # user = User(username='tan1997',password='19961021') # db.session.add(user) # db.session.commit() # 查询 # user = User.query.filter(User.username == 'tan1997').first() # print(user.username,user.password) # 修改 # user=User.query.filter(User.username == 'tan1997').first() # user.password=1234567 # db.session.commit() # 删除 # user=User.query.filter(User.username == 'tan1997').first() # db.session.delete(user) # db.session.commit() @app.route('/') def myweb(): return render_template("myweb.html") @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template("login.html") else: username = request.form.get('username') password = request.form.get('password') user = User.query.filter(User.username == username).first() if user: if user.password == password: session['user'] = username session.permannet = True return redirect(url_for('myweb')) else: return '密码错误' else: return '用户名不存在' @app.context_processor def mycontext(): usern = session.get('user') if usern: return {'username':usern} else: return {} @app.route('/regist/', methods=['GET', 'POST']) def regist(): if request.method == 'GET': return render_template("regist.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 redirect(url_for('login')) @app.route('/logout/') def logout(): session.clear() return redirect(url_for('myweb')) def loginfirst(func): @wraps(func) def wrapper(*args, **kwargs): if session.get('user'): return func(*args, **kwargs) else: return redirect(url_for('login')) return wrapper @app.route('/question/', methods=['GET','POST']) @loginfirst def question(): return render_template("question.html") if __name__ == '__main__': app.run(debug=True)