- 编写要求登录的装饰器
from functools import wraps
def loginFirst(func): #参数是函数
@wraps(func)
def wrapper(*args, ** kwargs): #定义个函数将其返回
#要求登录
return func(*args, ** kwargs)
return wrapper #返回一个函数
def loginFrist(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 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'))
- 完成发布函数。
@app.route('/question/',methods=['GET','POST']) @loginFrist def question(): if request.method == 'GET': return render_template('question.html') else: title = request.form.get('title') detail = request.form.get('detail') user=User.query.filter(User.username == session.get('user')).first() author_id = user.id question = Question.query.filter(Question.title == title).first() if question: return 'Question existed' else: question1 = Question(title=title, detail=detail, author_id=author_id) question1.author = user db.session.add(question1) # 保存到数据库 db.session.commit() # 提交 return redirect(url_for('home'))
{% extends 'base.html' %} {% block title %}Question{% endblock %} {% block head %} <link href="{{ url_for('static',filename='CSS/question.css') }}" rel="stylesheet" type="text/css"> {% endblock %} {% block main %} <div class="question"> <h3>Questions and answers</h3> <form action="{{ url_for('question') }}" method="post"> <div > <br> <label for="ask">Question</label> <br> <input name="title" type="text" style="height: 22px;" id="questionTitle"></input> </div> <br> <div> <label for="questionDetail">Detail</label> <br> <textarea name="detail" rows="8" id="questionDetail" ></textarea> </div> <br> <input type="checkbox"><p>Check me out</p> <button type="submit" class="btn-default">Release</button> </form> </div> {% endblock %}
保存到数据库。
重定向到首页。