zoukankan      html  css  js  c++  java
  • 11.28

    • 编写要求登录的装饰器

    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():
    def loginFirst(func):
        @wraps(func)
        def wrapper(*args,**kwargs):
            if session.get('user'):
                return func(*args,**kwargs)
            else:
                return redirect(url_for('denglu'))
        return wrapper
    
    @app.route('/wenjuan/',methods=['GET','POST'])
    @loginFirst
    def wenjuan():
        if request.method=='GET':
            return render_template('wenjuan.html')
        else:
            title=request.form.get('title')
            detail = request.form.get('detail')
            author_id = User.query.filter(User.username == session.get('user')).first().id
            wenjuan=question(title=title,detail=detail,author_id=author_id)
            db.session.add(wenjuan)
            db.session.commit()
            return redirect(url_for('shouye'))
    • 建立发布内容的对象关系映射。
    class Question(db.Model):
    class question(db.Model):
        __tablename__='question'
        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        author_id=db.Column(db.Integer,db.ForeignKey('user.id'))
        author=db.relationship('user',backref=db.backref('question'))
        title=db.Column(db.Text, nullable=False)
        detail=db.Column(db.Text, nullable=False)
        creat_time=db.Column(db.DateTime, nullable=False)
    • 完成发布函数。

    保存到数据库。

    重定向到首页。

     db.session.add(wenjuan)
            db.session.commit()
            return redirect(url_for('shouye'))
  • 相关阅读:
    Python内置函数(55)——round
    Python内置函数(54)——reversed
    Python内置函数(53)——repr
    Python内置函数(52)——range
    Python内置函数(51)——property
    Python内置函数(50)——print
    Python内置函数(49)——pow
    Python内置函数(48)——ord
    Python内置函数(47)——open
    Python内置函数(46)——oct
  • 原文地址:https://www.cnblogs.com/chenyanxi123/p/7908106.html
Copyright © 2011-2022 走看看