Flask request.args在新的应用路由中保持变量

时间:2018-11-08 21:02:07

标签: flask jinja2 html-form

我正在使用request.args获取变量。我想添加另一个应用程序路由以获得一个新变量,该变量将链接到应用程序路由“ / search /”中的client_id。添加其他应用程序路由时,如何保留此client_id变量?

from flask import Flask
from flask import render_template, url_for, request, redirect
from flask import make_response
app = Flask(__name__)
import pandas as pd


@app.route('/', methods=['GET'])
def index():
    res = '''<form action="/search" method=>
                    <p><input type="text" name="query" value="test"></p>
                    <p><input type="submit" value="Search"></p>
                    <br />
    </form>'''
    return res 

@app.route('/search', methods=["GET","POST"])
def suggestion():
    client_id = request.args['query']  
    return render_template('untitled2.html')


if __name__ == '__main__':
    app.run(debug=True) 

例如,我要添加此应用路线

@app.route('/csv/')
def download_csv():
    #can't figure out how to obtain the client_id var
    client_id = ??? 
    model_id=request.args['textid']
    model_id1=request.args['textid1']
    model_id2=request.args['textid2']

    # return response
    df=recommender.update_history(client_id, model_id, model_id1, model_id2)
    df= recommender.get_csv()
    resp = make_response(df.to_csv(encoding='iso-8859-1',index=False))
    resp.headers["Content-Disposition"] = "attachment; filename=export.csv"
    resp.headers["Content-Type"] = "text/csv"
    return resp

这是我的html模板上的内容,在这里我需要获取以前在request.args ['text']中的变量,并将其与新的表单数据一起发送到新的应用程序路由“ / csv”: / p>

untitled2.html:

 <div class="form-group">
            <h4>Suggestions for {{ request.args['text']  }}  </h4>
            <form action ="/csv">
             <form method="POST">
                <br>
                <label>Enter 3 suggestions</label>
                <br>
                <input name="textid", placeholder="Suggested Model ID #", value="{{ request.form['textid'] }}"/>
                <input name="textid1", placeholder="Suggested Model ID #", value="{{ request.form['textid1'] }}"/>
                <input name="textid2", placeholder="Suggested Model ID #", value="{{ request.form['textid2'] }}"/>

                <input type="submit" >
              </form>
          </div>

 <h4>Entered Suggestions:{{ request.form['textid'] }}  {{ request.form['textid1'] }}  {{ request.form['textid2'] }} </h4>

1 个答案:

答案 0 :(得分:1)

您可以保留client_id变量,方法是将其添加到会话中,将其保存在Cookie中或  使用g对象。

对于会话,只需使用client_id而不是session['client_id'] = request.args['query']。您始终可以使用session['client_id']来获取它。此外,您必须像app.config['SECRET_KEY'] = 'My secret key'这样在应用程序的配置中设置密钥。

详细了解会话here