Table of Contents
Introduction
In this tutorial, we will explore the fundamentals of Flask, a micro web framework for Python. We will cover Flask routes, which define the URLs that our application will respond to, and how to use templates to build dynamic HTML pages. Additionally, we will integrate Flask with SQLAlchemy, a popular Python SQL toolkit, to interact with a database.
By the end of this tutorial, you will have a good understanding of how to create routes, utilize templates for rendering dynamic content, and perform database operations using Flask-SQLAlchemy.
Prerequisites
Before starting this tutorial, you should have a basic understanding of Python programming. Knowledge of HTML and SQL will also be beneficial. It is recommended to have Python and Flask installed on your system.
Setup
To get started, let’s set up a new Flask project. Follow these steps:
- Create a new directory for your project and navigate into it using the terminal or command prompt:
mkdir flask_project cd flask_project
- Create a virtual environment to isolate your project’s dependencies:
python -m venv venv
- Activate the virtual environment:
source venv/bin/activate # For Mac/Linux venv\Scripts\activate # For Windows
- Install Flask:
pip install flask
Now we are ready to start building our Flask application!
Flask Routes
Flask routes define the mapping between the URLs and the Python functions that handle the corresponding requests. Let’s create a simple Flask route.
- Create a new file named
app.py
in your project directory:touch app.py
- Open
app.py
in a text editor and import Flask:from flask import Flask
- Initialize the Flask application:
app = Flask(__name__)
- Define a route and a function to handle the request:
@app.route('/') def home(): return 'Hello, Flask!'
The
@app.route('/')
decorator maps the URL/
to thehome()
function. When a user visits the root URL of our application, thehome()
function will be executed, and the string'Hello, Flask!'
will be returned to the user’s browser. - Add a main section to run the Flask application:
if __name__ == '__main__': app.run(debug=True)
- Save the file and run the application:
python app.py
- Open your browser and visit
http://127.0.0.1:5000
. You should see the message “Hello, Flask!” displayed.
Congratulations! You have created your first Flask route. Let’s move on to using templates to render HTML pages.
Templates
Templates allow us to separate the presentation logic from the application logic. Flask uses the Jinja2 templating engine to render dynamic HTML pages.
- Create a new directory named
templates
in your project directory:mkdir templates
- Create a new file named
index.html
inside thetemplates
directory, and open it in a text editor:touch templates/index.html
- In
index.html
, add the following HTML code:<!DOCTYPE html> <html> <head> <title>Flask Template</title> </head> <body> <h1>Welcome to Flask Template!</h1> <p></p> </body> </html>
- Modify the
home()
function inapp.py
to render the template:from flask import render_template @app.route('/') def home(): return render_template('index.html', message='Hello, Flask!')
The
render_template()
function takes the name of the template file as the first argument and any additional data to pass to the template as keyword arguments. In this case, we are passing the message'Hello, Flask!'
to be displayed in the template. - Save the changes and run the application again:
python app.py
- Refresh your browser at
http://127.0.0.1:5000
, and you should now see the heading “Welcome to Flask Template!” and the message “Hello, Flask!”.
Amazing! You have successfully rendered an HTML template using Flask. Let’s now integrate Flask with SQLAlchemy to work with a database.
Flask-SQLAlchemy
Flask-SQLAlchemy is an extension that provides simple integration of SQLAlchemy with Flask. SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapping (ORM) library for Python.
- Install Flask-SQLAlchemy:
pip install flask_sqlalchemy
- In
app.py
, importFlaskSQLAlchemy
and initialize it:from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' # SQLite database file path db = SQLAlchemy(app)
- Define a model class for your database table. For example, let’s create a
User
model:class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False)
- Create the database tables by running the following commands:
python from app import db db.create_all()
This will create a file named
database.db
in your project directory, which will hold the database tables. - Perform database operations inside Flask routes. Here’s an example of handling a POST request to create a new user:
from flask import request @app.route('/user', methods=['POST']) def create_user(): name = request.form['name'] user = User(name=name) db.session.add(user) db.session.commit() return 'User created successfully'
In this example, we access the form data submitted in the POST request using
request.form['name']
and create a newUser
object with the provided name. We then add the user to the database session, commit the changes, and return a success message. - Remember to import the required modules and include the necessary HTML forms in your templates.
Congratulations! You have integrated Flask with SQLAlchemy to perform database operations. Feel free to explore more advanced features of Flask and SQLAlchemy to build powerful web applications.
Conclusion
In this tutorial, we have covered Flask routes, templates, and Flask-SQLAlchemy. We learned how to define routes in Flask, use templates to render dynamic HTML pages, and integrate Flask with SQLAlchemy for database operations. By following this tutorial, you should now have a solid foundation to start building your own Flask applications.
Remember to practice and explore additional resources to further enhance your skills in Flask and web development with Python. Happy coding!