Table of Contents
- Introduction
- Prerequisites
- Setting Up
- Creating a Flask Application
- Routing and Handling Requests
- Rendering Templates
- Adding Forms and User Input
- Working with Databases
- Deployment
- Conclusion
Introduction
In this tutorial, we will learn how to build a web application using Flask, a popular Python web framework. By the end of this tutorial, you will be able to create your own Flask application and understand the basics of web development with Python.
Prerequisites
To follow along with this tutorial, you should have a basic understanding of Python programming. Familiarity with concepts like functions, variables, and control flow will be beneficial. Additionally, you should have Python and Flask installed on your machine.
Setting Up
Before we can start building our Flask application, we need to set up our development environment. Follow these steps to get started:
- Open your terminal or command prompt.
- Create a new directory for your project:
mkdir flask-app
- Navigate into the project directory:
cd flask-app
- Create a virtual environment:
python3 -m venv venv
- Activate the virtual environment:
- For Mac/Linux:
source venv/bin/activate
- For Windows:
venv\Scripts\activate
- For Mac/Linux:
- Install Flask:
pip install flask
With the setup complete, we are ready to start building our Flask application.
Creating a Flask Application
Let’s create a simple “Hello, World!” application to get familiar with Flask.
- Create a new Python file in your project directory, e.g.,
app.py
- Open the file with your preferred text editor.
- Import the Flask module:
from flask import Flask
- Create an instance of the Flask class:
app = Flask(__name__)
- Define a route and a handler function to handle requests:
@app.route('/') def hello(): return "Hello, World!"
- Add a conditional check to ensure the app is run directly:
if __name__ == '__main__': app.run()
Save the file and return to your terminal. Start the Flask development server by running
python app.py
. You should see a message indicating that the server is running. Open your web browser and navigate tohttp://localhost:5000
. You should see the “Hello, World!” message displayed on the page.
Routing and Handling Requests
In Flask, routes are used to map URLs to handler functions. Let’s create some additional routes and handle different types of requests.
- Define a new route for a contact page:
@app.route('/contact') def contact(): return "Contact Us"
- Add a route that accepts a dynamic parameter:
@app.route('/hello/<name>') def say_hello(name): return f"Hello, {name}!"
- Create a route that handles POST requests:
@app.route('/login', methods=['POST']) def login(): username = request.form.get('username') password = request.form.get('password') # Check username and password # ... return "Logged in successfully"
By adding these routes and handler functions to your
app.py
file, you can now navigate tohttp://localhost:5000/contact
to see the “Contact Us” page, orhttp://localhost:5000/hello/John
to greet the name “John”. Additionally, you can create an HTML form that submits a POST request tohttp://localhost:5000/login
and receive a “Logged in successfully” response.
Rendering Templates
Flask allows you to separate your application logic from your HTML templates. Let’s create a template for our “Hello, World!” page.
- Create a new directory inside your project directory called
templates
. - Inside the
templates
directory, create a new file calledhello.html
. - Open
hello.html
and add the following content:<!DOCTYPE html> <html> <head> <title>Hello Flask</title> </head> <body> <h1>Hello, World!</h1> </body> </html>
- Update your
app.py
file to render the template:from flask import render_template @app.route('/') def hello(): return render_template('hello.html')
Save both files and restart the Flask server. If you navigate to
http://localhost:5000
, you will see the same “Hello, World!” message, but this time it is rendered from the HTML template.
Adding Forms and User Input
One common requirement in web applications is to accept user inputs via forms. Flask makes it easy to handle form submissions.
- Create a new template called
login.html
in thetemplates
directory. - Add a login form to the
login.html
template:<!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form action="/login" method="POST"> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" value="Login"> </form> </body> </html>
- Update your
app.py
file to render thelogin.html
template for the/login
route.
Now, when you navigate to http://localhost:5000/login
, you will see a login form. When you submit the form, the data will be sent as a POST request to the /login
route, where you can access the form inputs and perform any necessary processing.
Working with Databases
To build more complex web applications, we often need to store and retrieve data from a database. Flask integrates well with various database systems.
- Install the Flask-SQLAlchemy extension:
pip install flask_sqlalchemy
- Add a configuration to your
app.py
file to specify the database URL:app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
- Create a new directory called
models
in your project directory. - Inside the
models
directory, create a new file calleduser.py
. - Define a User model in
user.py
using SQLAlchemy:from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) email = db.Column(db.String(50), nullable=False, unique=True) def __repr__(self): return f"<User {self.name}>"
- Initialize the database in your
app.py
file:from models.user import db db.init_app(app)
- Create a new route to handle user registration:
@app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': name = request.form.get('name') email = request.form.get('email') user = User(name=name, email=email) db.session.add(user) db.session.commit() return "User registered successfully" return render_template('register.html')
Now, whenever a user submits the registration form, their information will be stored in the database. You can retrieve and query the user data as needed.
Deployment
To make your Flask application accessible over the internet, you need to deploy it on a web server. There are various hosting options available, including cloud platforms and traditional web hosts.
One popular option is to deploy on a Platform-as-a-Service (PaaS) provider like Heroku. Follow these steps to deploy your Flask application on Heroku:
- Create a Heroku account (if you don’t have one already).
- Install the Heroku CLI by following the instructions on the Heroku website.
- Log in to the Heroku CLI using the command
heroku login
. - In your project directory, create a new file called
Procfile
and add the following content:web: gunicorn app:app
- Initialize a new Git repository and commit your code.
- Create a new Heroku app using the command
heroku create
. - Push your code to the Heroku remote repository using
git push heroku master
. - After the deployment process completes, you can access your Flask application using the URL provided by Heroku.
Congratulations! You have successfully deployed your Flask application to a live web server.
Conclusion
In this tutorial, we covered the basics of building a Flask application for web development. We started by setting up our development environment, creating routes, and handling different types of requests. We then explored rendering templates, accepting user inputs through forms, and integrating with databases. Finally, we learned how to deploy our Flask application to a web server.
Flask is a versatile web framework that offers many features and extensions, making it an excellent choice for building web applications with Python. With the knowledge gained from this tutorial, you can continue exploring Flask and its ecosystem to create more complex and feature-rich web applications.
Remember to refer to the Flask and SQLAlchemy documentation for more detailed information on specific topics and to expand your web development skills further.