问题
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)
回答1:
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()
回答2:
Option 1:
A variable created and updated inside a function exists only for that function.
From the Python documentation...
"If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global."
Solution:
Create q as a variable outside of functions, this way it's not just trapped inside function home but instead is now universally available to any and all functions. Any function can use or update such a variable.
Option 2:
Alternatively, you could just try passing q as a function parameter.
In example below, you will call function search but with parameter q added. The search function itself will reference that same q as a thing called input (or choose your own name/word).
@app.route("/",methods=['GET','POST'])
def home():
result = Mylist.query.all()
q = request.form.get("q")
search( q )
return render_template('index.html',result=result)
@app.route("/search.html")
def search( input ):
d = input
var='%'+d+'%'
result = Mylist.query.filter(Mylist.type.like(var)
return render_template('search.html',result=result)
回答3:
your 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")
来源:https://stackoverflow.com/questions/56088646/flask-pass-variable-from-one-function-to-another-function