from functools import wraps
def loginFirst(func): #参数是函数
@wraps(func)
def wrapper(*args, ** kwargs): #定义个函数将其返回
#要求登录
return func(*args, ** kwargs)
return wrapper #返回一个函数
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():
class Question(db.Model):
# /创建用户模型 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(50)) 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()
保存到数据库。
重定向到首页。
@app.route(‘/question/‘, methods=[‘GET‘, ‘POST‘]) @loginFirst def question(): if request.method == ‘GET‘: return render_template(‘question.html‘) else: title = request.form.get(‘title‘) detail = request.form.get(‘detail‘) author_id = User.query.filter(User.username == session.get(‘user‘)).first().id question = Question(title=title, detail=detail, author_id=author_id) db.session.add(question) db.session.commit() return redirect(url_for(‘shouye‘))
原文:http://www.cnblogs.com/yuanyinglin/p/7912504.html