Building web applications with Python is simpler than you might think, especially when using Flask, a lightweight yet powerful web framework. Whether you’re just getting started with web development or looking to expand your Python skills, this step-by-step tutorial will guide you through the entire process of creating a web application from scratch using Flask.
Post Contents
What is Flask?
Before diving into the tutorial, let’s quickly understand what Flask is. Flask is a micro-framework for Python that makes it easy to build web applications. Unlike larger frameworks like Django, Flask gives you the flexibility to choose which components you want to use. This makes it perfect for small to medium-sized applications or when you want more control over the tools you integrate.
Step 1: Setting Up Your Environment
The first step in building a Flask web application is to set up your development environment. You need Python installed on your system, as well as a virtual environment to manage your project dependencies.
Install Python and Pip
Ensure you have Python installed on your machine. If not, download it from the official Python website. You’ll also need pip
, the Python package manager, which usually comes pre-installed with Python.
Create a Virtual Environment
To keep your project dependencies isolated, it’s a good practice to use a virtual environment. To create one, navigate to your project folder and run:
python -m venv venv
Activate the virtual environment:
- On Windows:
venv\Scripts\activate
- On macOS/Linux:
source venv/bin/activate
Install Flask
Once your virtual environment is activated, install Flask using pip
:
pip install Flask
Now that Flask is installed, we’re ready to start building our web application.
Step 2: Creating Your First Flask Application
With Flask set up, let’s create a simple web application. Open your code editor and create a new file, app.py
. In this file, you’ll define your Flask application.
Basic Flask App Structure
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to my Flask web application!"
if __name__ == '__main__':
app.run(debug=True)
Here’s what’s happening:
- We import Flask and create an instance of the Flask class.
- The
@app.route('/')
decorator defines the URL route for the home page. - The
home()
function returns a message when someone visits the home page. - Finally, we use
app.run(debug=True)
to start the server in debug mode, making development easier by providing detailed error messages.
Running the App
To run your Flask app, open your terminal, navigate to your project directory, and type:
python app.py
Visit http://127.0.0.1:5000/
in your browser, and you should see the message “Welcome to my Flask web application!”
Step 3: Handling User Input with Flask
Let’s make the app more interactive by handling user input. We’ll create a simple form that allows users to submit their name, which will then be displayed on the page.
Adding a Form
First, modify your app.py
to include a route for the form:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/greet', methods=['POST'])
def greet():
name = request.form['name']
return f"Hello, {name}!"
if __name__ == '__main__':
app.run(debug=True)
Next, create an index.html
file in a folder called templates
. This will serve as the HTML form for users to input their name.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask App</title>
</head>
<body>
<h1>Enter your name:</h1>
<form action="/greet" method="POST">
<input type="text" name="name" placeholder="Your name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
When a user submits the form, their name will be displayed on the screen.
Step 4: Connecting Flask to a Database
Most web applications require a database to store and manage data. Flask can easily integrate with databases like SQLite, MySQL, or PostgreSQL. In this example, we’ll use SQLite, which is lightweight and perfect for small applications.
Install Flask-SQLAlchemy
We’ll use Flask-SQLAlchemy
, an extension that makes database integration seamless. Install it using pip
:
pip install Flask-SQLAlchemy
Setting Up the Database
Modify your app.py
to connect to the database and define a model for storing user data:
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/greet', methods=['POST'])
def greet():
name = request.form['name']
user = User(name=name)
db.session.add(user)
db.session.commit()
return f"Hello, {name}!"
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
Now, each time a user submits their name, it gets saved to the users.db
database.
Step 5: Deploying Your Flask Application
Once your application is ready, the final step is to deploy it. There are several platforms you can use to deploy Flask applications, such as Heroku, AWS, or PythonAnywhere. For simplicity, let’s look at how to deploy the app on Heroku.
Install Heroku CLI
Download and install the Heroku CLI from the official Heroku website.
Create a Procfile
In the root of your project directory, create a Procfile
with the following content:
web: gunicorn app:app
This tells Heroku to use gunicorn
to run your app.
Push to Heroku
Initialize a Git repository in your project folder and push the app to Heroku:
git init
heroku create
git add .
git commit -m "Initial commit"
git push heroku master
Your Flask app is now live on the web!
Conclusion
Following, this step-by-step tutorial, you’ve learned how to build a web application using Python and Flask. From setting up the environment to deploying your app, each step brings you closer to mastering Flask. The more you practice, the easier it will be to create more complex applications with Python and Flask.