Setting Up a Flask App with SQLite Database
Flask is a lightweight and flexible web framework for Python that is perfect for building web applications quickly and easily. When paired with SQLite, a simple and efficient database engine, you have all the tools needed to create robust applications. This guide will walk you through setting up a Flask app with an SQLite database.
Prerequisites
Before starting, ensure you have Python and pip installed on your system. You can check their versions by running the following commands:
If they are not installed, download and install Python from python.org.
Setting Up the Project
Create a new directory for your project and navigate into it:
Create and activate a virtual environment:
Install Flask and the SQLite extension for Python:
Project Structure
Your project directory should look like this:
Create the necessary directories and files:
Setting Up the Flask App
In app.py
, start by importing Flask and setting up the application:
This script sets up a basic Flask application with SQLAlchemy to interact with an SQLite database. The Item
class defines the structure of our table.
Creating the Database
The db.create_all()
command creates the database with the defined schema if it doesn't exist. This command is executed when the application starts if the database file is not found.
Creating Templates
Create an index.html
file in the templates
directory to display the items and provide a form to add new items:
Running the Application
Start your Flask application:
Open your web browser and navigate to http://127.0.0.1:5000/
. You should see the item list and a form to add new items. Items added through the form will be saved to the SQLite database and displayed on the page. You can also delete items using the delete link next to each item.
Conclusion
You've now set up a basic Flask application with an SQLite database. This setup provides a solid foundation for developing more complex web applications. Flask's simplicity and flexibility, combined with SQLite's lightweight database engine, make this stack an excellent choice for small to medium-sized applications. Happy coding!
Last updated