Flask - Get keys and values from URL
by
Jeremy Canfield |
Updated: November 25 2024
| Flask articles
Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.
- Model -> models.py
- View -> views.py
- Controller -> __init__.py
Let's say your flask project has the following structure.
├── main.py
├── database (directory)
│ ├── example.db
├── my-project (directory)
│ ├── __init__.py
│ ├── views.py
│ ├── models.py
│ ├── templates (directory)
│ │ ├── base.html
│ │ ├── home.html
│ │ ├── results.html
│ └── static (directory)
│ └── custom.css
Let's say a request is submitted to the /Test route of your Flask application with the following parameters.
http://www.example.com/Test?foo=Hello&bar=World
request can be used to get the values (Hello and World) from the keys (foo and bar).
In your view (views.py in this example), here is how you could print the values to your terminal console.
#!/usr/bin/python3
from flask import request
@views.route('/Test', methods=['GET', 'POST'])
def test():
print(f"foo = {request.args.get('foo')}") <- Hello
print(f"bar = {request.args.get('bar')}") <- World
return render_template('test.html')
Here is an example with error handling.
#!/usr/bin/python3
from flask import request
@views.route('/Test', methods=['GET', 'POST'])
def test():
try:
request.args.get('foo')
except KeyError:
print(f"got KeyError - there is no foo URL parameter")
example NameError:
print(f"got NameError - the foo URL parameter contains no value")
else:
print(f"foo = {request.args.get('foo')}")
return render_template('test.html')
Did you find this article helpful?
If so, consider buying me a coffee over at