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():
@app.route(‘/questions/‘,methods=[‘GET‘,‘POST‘]) @loginFirst def questions(): if request.method == ‘GET‘: return render_template(‘questions.html‘) else: title = request.form.get(‘title‘) detail = request.form.get(‘detail‘) author_id = User.query.filter(User.username == session.get(‘user‘)).first().id questions = Question(title=title, detail=detail, author_id=author_id) db.session.add(questions) db.session.commit() return redirect(url_for(‘index‘))
class Question(db.Model):
保存到数据库。
重定向到首页。
class Question(db.Model): __tablename__ =‘questions‘ 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) create_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(‘questions‘))
原文:http://www.cnblogs.com/BerylF/p/7912687.html