Flask is a lightweight web framework for Python that is simple to use, flexible, and powerful for building web applications. It’s ideal for small to medium-sized projects and offers more control and customization than larger frameworks like Django. In this tutorial, we’ll cover the basics of Flask, including creating a simple web application, routing, and using templates.
1. Introduction to Flask
Flask is a micro-framework, meaning it provides the essential tools for building web applications but leaves other features, such as database integration or form validation, to be added as needed. Flask is designed to be minimal and easy to extend, making it a great choice for beginners and experienced developers alike.
2. Installing Flask
Before you start using Flask, you need to install it. You can install Flask using pip
.
pip install Flask
3. Creating a Basic Flask Application
To create a basic Flask application, you need to import the Flask
class and instantiate an app. Then, you define routes to specify how URLs map to functions in your application.
3.1 Your First Flask Application
from flask import Flask # Create a Flask app instance app = Flask(__name__) # Define a route for the home page @app.route('/') def home(): return "Hello, Flask!" # Run the app if __name__ == "__main__": app.run(debug=True)
To run the app, save the code in a Python file (e.g., app.py
) and execute it. Open your browser and go to http://127.0.0.1:5000/
to see the output.
4. Understanding Routes
In Flask, routes are defined using the @app.route
decorator. The route specifies the URL pattern that triggers a function when accessed.
4.1 Defining Additional Routes
You can define as many routes as needed for your application.
@app.route('/about') def about(): return "This is the About page"
Now, if you visit http://127.0.0.1:5000/about
, you will see the “This is the About page” message.
5. Using Templates in Flask
Flask makes it easy to return HTML by using Jinja2 templates. Jinja2 allows you to embed Python code inside HTML files.
5.1 Creating a Template
First, you need to create a directory called templates
in the same folder as your Flask app. Inside that directory, create an HTML file (e.g., index.html
).
Flask Template Example {{ message }}
5.2 Rendering a Template in Flask
To render the template, you use the render_template
function provided by Flask. Pass any data you want to display in the template as keyword arguments.
from flask import render_template @app.route('/') def home(): return render_template('index.html', message="Hello, Flask with Templates!")
When you visit http://127.0.0.1:5000/
, the page will display the message passed to the template.
6. Working with Dynamic Data in Templates
You can pass dynamic data to templates, such as user input or data retrieved from a database.
6.1 Passing Multiple Variables to Templates
@app.route('/user/') def user(name): return render_template('user.html', user_name=name)
6.2 Creating a Dynamic Template
Now, create a user.html
template:
User Page Hello, {{ user_name }}!
Now, visiting http://127.0.0.1:5000/user/John
will display “Hello, John!” on the page.
7. Flask HTTP Methods
Flask supports multiple HTTP methods, such as GET, POST, PUT, DELETE, etc. By default, Flask routes respond to GET requests, but you can specify other methods.
7.1 Handling POST Requests
In a form submission, you typically use the POST method to send data. Here’s an example:
from flask import request @app.route('/submit', methods=['POST']) def submit(): name = request.form['name'] return f"Hello, {name}!"
7.2 Creating a Form Template
Create a form in an HTML template that sends data via POST:
8. Running the Flask Application
To run the Flask application, use the following command in your terminal:
python app.py
Your Flask app will be available at http://127.0.0.1:5000/
by default. To stop the app, press Ctrl+C
in the terminal.
Conclusion
In this tutorial, you’ve learned how to create a simple web application using Flask. We covered topics such as routing, rendering templates, handling dynamic data, and using HTTP methods. Flask is a versatile web framework that can be used for everything from small projects to large-scale applications.