Welcome back, coding enthusiasts! Today, we're diving deep into the world of Flask and exploring how to work with Query Parameters using request.args.
Query parameters are a common way to pass data from a client (like a browser) to a server (like a Flask application). They are a part of the URL and can be used to customize the response of a web application. Let's get started! šÆ
Query parameters are additional information appended to a URL after a ? symbol. They are key-value pairs that help to customize a server's response based on user input. Here's an example:
http://example.com/?name=John&age=30
In this example, name=John and age=30 are query parameters.
First, let's create a new Flask application and install the necessary packages.
pip install flaskNow, create a new file named app.py and add the following code to set up a basic Flask application.
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to CodeYourCraft Flask Tutorials!"
if __name__ == '__main__':
app.run(debug=True)Now, let's run the application and see the response.
python app.pyNow, let's modify our application to accept and display query parameters.
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def home():
name = request.args.get('name')
age = request.args.get('age')
if name and age:
return f"Welcome, {name}! You are {age} years old."
else:
return "No query parameters provided."
if __name__ == '__main__':
app.run(debug=True)In the modified code, we're accessing query parameters using the request.args.get() function. This function returns the value of a query parameter if it exists, or None otherwise.
Now, let's make our application more practical by creating a simple search form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Query Parameters</title>
</head>
<body>
<form action="/">
<label for="search">Search:</label>
<input type="text" id="search" name="search">
<input type="submit" value="Submit">
</form>
</body>
</html>Save this code as index.html and place it in the same directory as app.py. Now, when you run the application, you should see a search form. Enter a search term and click Submit to see the response.
What is the purpose of Query Parameters?
That's it for today! You've learned how to work with Query Parameters using Flask and the request.args object. With this knowledge, you can create more dynamic and customizable web applications.
Stay tuned for our next tutorial, where we'll explore more advanced features of Flask! š
š” Pro Tip: Always validate and sanitize user input to prevent security vulnerabilities.
š Note: Flask also supports POST requests and JSON data. We'll cover that in future tutorials.
š” Pro Tip: Check out the Flask documentation for more detailed information and examples.
Happy coding! ā