How can I get the named parameters from a URL using Flask?
Use request.args
to get parsed contents of query string:
from flask import request
@app.route(...)
def login():
username = request.args.get('username')
password = request.args.get('password')
Get a variable from the URL in a Flask route
This is answered in the quickstart of the docs.
You want a variable URL, which you create by adding <name>
placeholders in the URL and accepting corresponding name
arguments in the view function.
@app.route('/landingpage<id>') # /landingpageA
def landing_page(id):
...
More typically the parts of a URL are separated with /
.
@app.route('/landingpage/<id>') # /landingpage/A
def landing_page(id):
...
Use url_for
to generate the URLs to the pages.
url_for('landing_page', id='A')
# /landingpage/A
You could also pass the value as part of the query string, and get it from the request, although if it's always required it's better to use the variable like above.
from flask import request
@app.route('/landingpage')
def landing_page():
id = request.args['id']
...
# /landingpage?id=A
Get a variable from the URL to all Flask routes
It appears that you're using a form in home.html
for capturing the answer. For capturing the question, you could add a hidden field to the same form, which you'd pre-populate via templating.
Alternatively, you could use GET /<question>
for serving the question, and POST /<question>
for checking the answer. In that case, you could use something like:
@app.route('/<question>', methods=['GET', 'POST'])
def route_question (question):
if request.method == 'GET':
return render_template('home.html', code=questions_dict.get(question))
# otherwise ...
answer = request.form['answer']
if answer and answer == answers_dict.get(question):
full_filename = os.path.join('static', 'test.jpg')
return render_template('your_url.html', user_image = full_filename)
# otherwise ...
return render_template('again.html', code=questions_dict.get(question))
Do ensure that the form in home.html
uses POST, i.e: <form method="POST">
.
Such a solution would also apply with regard to similar WSGI frameworks, like Bottle and Vilo.
Passing variables through URL to a flask app
The first route describes a url with a value as part of the url. The second url describes a route with no variables, but with a query parameter in the url.
If you are using the first route, the url should look like http://127.0.0.1/changeip/1.2.2.2
.
If you are using the second url, the route should look like /changeip
, the function should be def change_ip():
, and the value should be read from request.args['ip']
.
Usually the route should describe any arguments that should always be present, and form or query params should be used for user-submitted data.
Passing variable from JavaScript to flask route
If you want to transfer your javascript variable to your flask route kindly check my answer here:
Why does my data come from request.form when passing it to the backend in Flask, python?
- Ajax/Fetch
JavaScript
var your_data = {
/* name */ : /* value */
}
fetch(`${window.origin}/your_url`, {
method: "POST",
credentials: "include",
body: JSON.stringify(your_data),
cache: "no-cache",
headers: new Headers({
"content-type": "application/json"
})
})
Python
@app.route("/your_url", methods = ["post"])
def printer():
data = request.get_json()
print(data)
return "TODO"
However if you want to render a template (like a form submit would do) then you can do this:
A. Doing it inside a hidden form
HTML
<form id="mainform" action="/your_url" method="post">
<input type="hidden" name="jsvar" id="jsvar" value="" />
<button type="submit">Click Me</button>
</form>
JavaScript
var form = document.getElementById("mainform")
var input = document.getElementById("jsvar")
form.addEventListener('submit', function(e){
input.value = "your_var"
form.submit()
})
Python
@app.route("/test",methods=["POST"])
def proposeswap_db_function():
print("inside function")
data = request.form["jsvar"]
print(data)
print('rendering mainmenu')
return f"{data}"
Getting a variable from url in Flask to use outside a function
import os, json, subprocess, sys
import CallExternalServiceConfig as c
from flask import Flask, jsonify
DATAS = "datas"
SOURCE_FOLDER = "source_folder"
NAME_SCRIPT = "name_script"
PARAMETERS = "parameters"
app= Flask(__name__)
@app.route('/Test/<string:jsonname>/')
def action():
json_name = request.args.get('jsonname', default = '', type = str)
with open(json_name + ".json", "r") as read_file:
data = json.load(read_file)
for trigger in data[DATAS]:
adress=trigger[SOURCE_FOLDER]
namescript=trigger[NAME_SCRIPT]
parameter=trigger[PARAMETERS]
subprocess.call([adress+namescript, parameter.split(",")], shell=True)
print(parameter.split(","))
return jsonify(adress+namescript)
if __name__ == "__main__":
app.run(host=c.get(c.SERVER_HOST, '127.0.0.1'), port=int(c.get(c.SERVER_PORT,
'5000')));
Can't retrieve variable from url with Flask app after submitting search form
You're confusing url parameters, which are captured with <variable>
, with query parameters, which are accessed in request.args
. Remove the query parameter from your route definition and access it in the view.
from flask import request
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search')
def search():
search = request.args.get('search') # will be None if form wasn't submitted
# do something with search
return render_template('search.html', search=search)
index.html
:
<form action="{{ url_for('search') }}">
<input name="search"/>
<input type="submit" value="Search"/>
</form>
In python flask, how do you get the path parameters outside of the route function?
It's possible to use request.view_args
.
The documentation defines it this way:
A dict of view arguments that matched the request.
Here's an example:
@app.route("/data/<section>")
def data(section):
assert section == request.view_args['section']
Flask url with variable input
If you using parametrizing url you can use function with parameters:
# url to call will be:
# genreport/1/2
@app.route('/genreport/<lid>/<userID>')
def pdf_template(lid, userID):
print(lid, userID)
# lid = request.form['lid']
# userID = request.form['userID']
Second option use url parameters, you should use request.args.get:
# url to call will be:
# genreport?lid=1&userID=2
@app.route('/genreport')
def pdf_template():
lid = request.args.get('lid')
userID = request.args.get('userID')
print(lid, userID)
Related Topics
What Is the Use of "Assert" in Python
How to Use Phantomjs in Python
Passing a Dictionary to a Function as Keyword Parameters
Common Elements Comparison Between 2 Lists
Pip Install from Pypi Works, But from Testpypi Fails (Cannot Find Requirements)
How to Change the X Axis in Matplotlib So There Is No White Space
Using an Numpy Array as Indices of the 2Nd Dim of Another Array
Creating an Empty Pandas Dataframe, Then Filling It
Stripping Everything But Alphanumeric Chars from a String in Python
How to Catch and Print the Full Exception Traceback Without Halting/Exiting the Program
Remove Pandas Rows with Duplicate Indices
Why Should I Make a Copy of a Data Frame in Pandas
Generate Random Numbers with a Given (Numerical) Distribution
Convert Python Datetime to Epoch with Strftime
Multiprocessing: How to Share a Dict Among Multiple Processes
Python - Pip Install Trouble Shooting - Permissionerror: [Winerror 5] Access Is Denied