Home >Backend Development >Python Tutorial >How to Access Query Parameters in Flask Routes?
Accessing Query Parameters in Flask Routes
Flask provides convenient methods to access query parameters in route handlers. Query parameters are the key-value pairs that follow the question mark (?) in a URL. They are often used to pass additional information to server-side scripts.
Solution:
To access query parameters or the query string in Flask routes, use the request.args object. The request object is available in all route handlers and contains a dictionary-like args attribute. The keys of this dictionary are the query parameter names, and the values are the corresponding values.
For example, the following route handler retrieves the value of the abc query parameter:
<code class="python">@app.route('/data') def data(): # Here we want to get the value of abc (i.e. ?abc=some-value) abc = request.args.get('abc')</code>
If the client requests example.com/data?abc=123, the abc variable will contain the string 123.
Complete Example:
The following code provides a complete example of a Flask route handler that uses query parameters:
<code class="python">from flask import request @app.route('/data') def data(): # Here we want to get the value of abc (i.e. ?abc=some-value) abc = request.args.get('abc') if abc: # Do something with the parameter value print(f"User entered: {abc}") else: # Handle the case where 'abc' is not specified print("Query parameter not provided") # You can also access the entire query string as a string query_string = request.args.to_dict() print(f"Query string: {query_string}")</code>
The above is the detailed content of How to Access Query Parameters in Flask Routes?. For more information, please follow other related articles on the PHP Chinese website!