flask pass variable from one function to another function

nupur picture nupur · May 11, 2019 · Viewed 7.5k times · Source

As you can see the code. I want to pass variable q from function home() into function search().

@app.route("/",methods=['GET','POST'])
def home():
    result = Mylist.query.all()
    return render_template('index.html',result=result)
    q = request.form.get("q")

@app.route("/search.html")
def search():
        d = q
        var='%'+d+'%'
        result = Mylist.query.filter(Mylist.type.like(var)
        return render_template('search.html',result=result)

Answer

nupur picture nupur · May 13, 2019

Where an index.html will contain:

<form action="/search.html" method="get" autocomplete="off" class="subscribe-form">
     <div class="form-group d-flex">
         <input type="text" class="form-control" placeholder="Enter your search" name="q" id="q" value="{{q}}">
         <input type="submit" value="Search" class="submit px-3">
     </div>
 </form>

Now you will see /search.html?q=top in url now you can easily pass this q=top by using q=request.args.get("q")...

@app.route("/search.html",methods=['GET'])
def search():
        q =request.args.get("q")
        d=str(q)
        var='%'+d+'%'
        myresult = Mylist.query.filter(Mylist.type.like(var)| Mylist.title.like(var)).all()