Seeking advice: What is my best way to pass a variable between Flask routes?
You can store it as session data, for instance:
from flask import request, session
def get_year():
try:
session["year"] = request.form['year']
except KeyError:
pass
return session.get("year") # if "year" hasn't been set yet, return None
How do i pass a variable to all flask routes once?
You can do so by creating a custom render template function using the following implementation
from flask import render_template as real_render_template
from yourapp import user # Import the user variable or set it
def render_template(*args, **kwargs):
return real_render_template(*args, **kwargs, user=user)
it can also be done via functools.partial
:
from flask import render_template as real_render_template
from yourapp import user # Import the user variable or set it
from functools import partial
render_template = partial(real_render_template, user=user)
Flask : how to pass variables between html pages app route
Use the session to store data between requests from the same client.
from flask import session
def getvlan():
session['vlanid'] = request.form['vlanid']
return redirect(url_for('showvlan'))
def showvlan():
vlanid = session['vlanid']
...
Use a database (or other external, persistent store) to store data in a more generally accessible sense.
How to pass variables between HTML pages using Flask
So i didn't got your approach.Below is what i did,I changed the code a bit. Hope this solves your problem.
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/form', methods = ['GET', 'POST'])
def form():
if request.method == 'POST':
glon = request.form['glon']
return render_template('display.html', glon=glon)
# @app.route('/return_form/<glon>', methods = ['GET', 'POST'])
# def return_form(glon):
# return render_template('return_form.html', glon=glon)
if __name__ == '__main__':
app.run()
index.html
<html>
<body>
<form action ="{{ url_for('form') }}" method="post">
Galactic Longitude: <input type="text" name="glon">
<button type="submit">Submit</button>
</form>
</body>
</html>
display.html
<!doctype html>
<body>
<p> {{ glon }} </p>
</body>
</html>
How can I pass a variable to a python flask app?
global myvariable=8
@app.route("/myrout", methods=["GET"])
def myfunction():
global myvariable
local_variable=myvariable
How to pass variable onto another route in FLASK
The problem is the way your code is organized. Variables in a function are scoped within the function, so books
isn't available from the second route. In addition to that, you have a naming collision where books=books
is referring to the function itself (which is defined at the module scope).
If you want to share code between routes, put it in a separate function:
def get_books(query, show_nav_bar=False):
query = query.lower()
query_like = '%' + query + '%'
books = db.execute('SELECT * FROM books WHERE (LOWER(isbn) LIKE :query) OR (LOWER(title) LIKE :query) '
'OR (LOWER(author) LIKE :query)', {'query': query_like}).fetchall()
if not books:
return render_template('error.html', message='No Books were Found!', navbar=True)
return render_template('books.html', query=query, books=books, navbar=show_nav_bar)
@app.route("/search", methods=['GET', 'POST'])
def search():
if request.method == 'GET':
return render_template('search.html', navbar=True)
else:
return get_books(request.form.get('query'), show_nav_bar=True)
@app.route("/books", methods=['GET', 'POST'])
def books():
return get_books(request.form.get('query'))
flask pass variable from one function to another function
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()
Related Topics
How to Read CSV Data into a Record Array in Numpy
Path Issue With Pytest 'Importerror: No Module Named Yadayadayada'
How to Fill Out a Python String With Spaces
How to Format a Floating Number to Fixed Width in Python
Convert [Key1,Val1,Key2,Val2] to a Dict
How to Test If a String Contains One of the Substrings in a List, in Pandas
How to Create a List of Random Numbers Without Duplicates
Is There a Zip-Like Function That Pads to Longest Length
Refering to a Directory in a Flask App Doesn't Work Unless the Path Is Absolute
How to Chain the Movement of a Snake'S Body
Checking Whether a Variable Is an Integer or Not
How to Call a Function from Another .Py File
How to List All Functions in a Module
Sorting Arrays in Numpy by Column
Sort a List of Tuples by 2Nd Item (Integer Value)
How to Use Pickle to Save a Dict (Or Any Other Python Object)
Convert a Pandas Dataframe to a Dictionary
How to Translate an Iso 8601 Datetime String into a Python Datetime Object