【问题标题】:How do you pass values between routes in flask? [duplicate]你如何在烧瓶中的路线之间传递值? [复制]
【发布时间】:2021-08-25 08:13:28
【问题描述】:

在 Flask 中渲染模板时如何将值传递给路由?

@ui.route('/login', methods=['GET' , 'POST'])
def login():
    
    usr = User.query.filter_by(username=username).first()
    if request.method == "POST":
        ## login code
        username = request.form.get('username')
        if not check_password_hash(user.password, password):
            flash('Wrong creds')

            return render_template('login.html')
        else:
            return render_template('profile.html', usrname=username) 
        return render_template('login.html')
       

目标是将 User 对象的用户名传递给 PROFILE 路由,以便用户看到他的个人资料

@ui.route('/PROFILE/<usrname>', methods=['GET','POST'])

def PROFILE(usrname):

    usr = User.query.filter_by(username=usrname).first()
    if request.method == "POST":
        TEXT =request.form.get('text')
        usr.text = TEXT
        db.session.add(usr)
        db.session.commit()
    else:
        render_template('add_text.html')

【问题讨论】:

    标签: flask


    【解决方案1】:

    使用url_for重定向内部路由

    伪代码

    from flask import Flask, redirect, url_for
    .
    .
    .
    @ui.route('/login', methods=['GET' , 'POST'])
    def login():
    
        usr = User.query.filter_by(username=username).first()
        if request.method == "POST":
            ## login code
            username = request.form.get('username')
            if not check_password_hash(user.password, password):
                flash('Wrong creds')
    
                return render_template('login.html')
            else:
                redirect(url_for(f'/PROFILE/{username}') 
            return render_template('login.html')
    

    【讨论】:

      【解决方案2】:

      你可以使用redirect和url_for

      @ui.route('/login', methods=['GET' , 'POST'])
      def login():
          
          usr = User.query.filter_by(username=username).first()
          if request.method == "POST":
              ## login code
              username = request.form.get('username')
              if not check_password_hash(user.password, password):
                  flash('Wrong creds')
      
                  return render_template('login.html')
              else:
                  return redirect(url_for('.PROFILE', usrname=username))
                  # here url_for takes the function name 
              return render_template('login.html')
      

      【讨论】:

        猜你喜欢
        • 2020-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-31
        • 1970-01-01
        • 2017-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多