Explain Codes LogoExplain Codes Logo

How do you access the query string in Flask routes?

python
prompt-engineering
functions
response-objects
Anton ShumikhinbyAnton Shumikhin·Oct 29, 2024
TLDR

In Flask, simply use the request module to access query parameters:

# Import all you need from Flask from flask import request @app.route('/search') def search(): # Where the magic happens query = request.args.get('parameter_name')

Given a URL http://example.com/search?item=book, snag that item value with the following code:

from flask import request @app.route('/search') def search(): # One book please, and make it snappy! item = request.args.get('item') # Returns 'book' or None if not in the mood

With request.args.get(), you not only get to the values but also avoid those pesky KeyError exceptions. It's like having your cake and eating it too, but in a more Flask-y way.

Ensuring a secure retrieval of parameters

Just as you wouldn't eat unwashed fruit, don't use raw query parameters without sanitizing them. XSS attacks are a real threat, but Flask's got your back with the escape method:

from flask import request, escape @app.route('/search') def search(): # Now washing... Please wait! 🧽 item = escape(request.args.get('item'))

Now, you can use your parameters without worrying about harmful characters, sort of like eating an apple without fearing worms.

Dealing with multiple parameters at once

We all love multi-tasking, right? Similarly, request.args allows us to access all the parameters like a dictionary, because who likes doing things one at a time?

from flask import request @app.route('/data') def data(): parameters = request.args # Dictionary-like object` for key, value in parameters.items(): # I see you (key:value)! print(f"{key}: {value}")

Or if you prefer, think of it as having a tool in Flask that is as close to telekinesis as you might get. You can just unpack the query parameters directly:

from flask import request @app.route('/data') def data(): # I'll take item and user for 200, Alex. item, user = request.args.get('item'), request.args.get('user')

The raw power of the raw query string

Sometimes, you want the whole shebang—the unparsed query string. Retrieve it with Flask's request.query_string:

from flask import request @app.route('/data') def data(): # Who ordered the raw string? raw_query = request.query_string.decode()

Organizing routes with Blueprints

For those days when you look at your routes and feel overwhelmed (it happens!), introduce yourself to Flask Blueprints. They help you to break down your application into more manageable chunks of routes:

from flask import Blueprint # The new kid on the block with its own routes mod = Blueprint('mod', __name__) # mod's route, not your app's! @mod.route('/data') def data(): # Found user in mod! Told you he was hiding somewhere! user = request.args.get('user')

But remember the golden rule: blueprints are invisible until you call app.register_blueprint():

app.register_blueprint(mod, url_prefix='/module')

Handling your query with custom responses

The king of the query handling kingdom is, without a doubt, the Response object from Flask. You get to give custom responses depending on the parameters:

from flask import request, Response @app.route('/data') def data(): # Some detective work here! user = request.args.get('user') if user: # Master Detective to user: I Found You! return Response(f"User found: {user}", status=200) return Response("User parameter must be on vacation", status=400)

Demystifying complex query parsing

Now assume the URL has a more complex query string:

Flask Route (🏠): /results Query String (🔑): ?type=report&year=2021&sort_by=date

Let's unlock this puzzle:

from flask import request @app.route('/results') def results(): # Getting all the goods! report_type = request.args.get('type') year = request.args.get('year') sorting = request.args.get('sort_by') # Now just trigger the fireworks!

References