- 编写要求登录的装饰器
from functools import wraps
def loginFirst(func): #参数是函数
@wraps(func)
def wrapper(*args, ** kwargs): #定义个函数将其返回
#要求登录
return func(*args, ** kwargs)
return wrapper #返回一个函数
- 应用装饰器,要求在发布前进行登录,登录后可发布。
@app.route('/question/',methods=['GET','POST']) @loginFirst def question():
- 建立发布内容的对象关系映射。
class Question(db.Model):
- 完成发布函数。
保存到数据库。
重定向到首页。
from flask import Flask,render_template,request,redirect,url_for,sessionfrom flask_sqlalchemy import SQLAlchemyfrom functools import wrapsfrom datetime import datetimeimport configapp = Flask(__name__)app.config.from_object(config)db=SQLAlchemy(app)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)class Question(db.Model): __tablename__ = 'question' id = db.Column(db.Integer, primary_key=True, autoincrement=True) question = db.Column(db.String(100), nullable=False) questionDetail = 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()@app.route('/')def homepage(): return render_template("homepage.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 sessionpermanent = True return redirect(url_for('homepage')) else: return 'password error' else: return 'username is not existed'@app.route("/register/",methods=['GET','POST'])def register(): if request.method == "GET": return render_template("register.html") else: username = request.form.get("username") password = request.form.get("password") user = User.query.filter(User.username == username).first() if user: return 'username existed.' else: user = User(username=username, password=password) db.session.add(user) db.session.commit() return redirect(url_for('login'))@app.context_processordef mycontext(): usern = session.get('user') if usern: return {'username':usern} else: return {}@app.route('/logout/')def logout(): session.clear() return render_template("homepage.html")def log(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'])@logdef question(): if request.method == 'GET': return render_template('question.html') else: question = request.form.get('question') questionDetail = request.form.get('questionDetail') author_id = User.query.filter(User.username == session.get('user')).first().id question = Question(question = question, questionDetail = questionDetail, author_id = author_id) db.session.add(question) db.session.commit() return redirect(url_for('homepage'))if __name__ == '__main__': app.run(debug=True)