Introduction
Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. Flask has become one of the most popular web frameworks due to its simplicity and flexibility.
In this post, we'll explore how to get started with Flask, including installation and creating a simple web application.
Why Flask?
Flask is known for its simplicity and ease of use. It allows developers to build web applications quickly with minimal setup. Some of the key features of Flask include:
Lightweight: It’s a microframework, so it’s small and easy to get started with.
Modular: Components can be used independently or together.
Flexible: Provides simplicity while giving the power to add complexity as needed.
Extensible: Supports extensions to add functionality.
Installation
To start using Flask, you need to have Python installed on your system. Flask works with Python 3.6 and higher. You can check if Python is installed by running:
python --version
If Python is installed, you should see something like Python 3.x.x
. If not, download and install Python from python.org.
Once Python is installed, you can install Flask using pip:
pip install Flask
To verify Flask is installed correctly, you can run:
python -m flask --version
You should see the version of Flask that was installed.
Creating Your First Flask Application
Let's create a simple "Hello, World!" application using Flask. Follow these steps:
Step 1: Set Up the Project
Create a new directory for your project and navigate into it:
mkdir my_flask_app
cd my_flask_app
Step 2: Create a Virtual Environment
It’s good practice to create a virtual environment for your project to manage dependencies:
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
Step 3: Install Flask in the Virtual Environment
pip install Flask
Step 4: Create the Application File
Create a new file called app.py
and open it in your text editor. Add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
Step 5: Run the Application
Run the application by executing:
python app.py
You should see output indicating that the server is running, something like:
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Open your web browser and navigate to http://127.0.0.1:5000/
. You should see "Hello, World!" displayed on the page.
Exploring Flask Features
Now that you have a basic Flask application running, let's explore some additional features:
Adding Routes
You can add more routes to handle different URLs. For example:
@app.route('/about')
def about():
return "This is the about page."
@app.route('/contact')
def contact():
return "This is the contact page."
Using Templates
Flask supports templates to render HTML. Create a directory called templates
and add an index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<h1>{{ message }}</h1>
</body>
</html>
Modify app.py
to render this template:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', message="Hello, Flask!")
if __name__ == '__main__':
app.run(debug=True)
Handling Forms
Flask can handle form submissions. Create a form in your template:
<form action="/submit" method="post">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
Add the route to handle the form data:
from flask import request
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['name']
return f"Hello, {name}!"
Conclusion
Flask is a powerful and flexible web framework for Python. Its simplicity makes it a great choice for beginners, while its extensibility ensures that even advanced users can create complex applications. In this post, we covered the basics of installing Flask, creating a simple web application, adding routes, using templates, and handling forms.
Happy coding!