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:
python --version
pip --version
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:
mkdir flask-sqlite-app
cd flask-sqlite-app
Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
Install Flask and the SQLite extension for Python:
pip install Flask
Project Structure
Your project directory should look like this:
flask-sqlite-app/
│
├── venv/
├── app.py
├── templates/
│ └── index.html
└── instance/
└── app.db
Create the necessary directories and files:
mkdir templates
mkdir instance
touch app.py
touch templates/index.html
Setting Up the Flask App
In app.py
, start by importing Flask and setting up the application:
flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
# Configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../instance/app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Models
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
description = db.Column(db.String(200), nullable=False)
def __repr__(self):
return f'<Item {self.name}>'
# Routes
@app.route('/')
def index():
items = Item.query.all()
return render_template('index.html', items=items)
@app.route('/add', methods=['POST'])
def add_item():
name = request.form['name']
description = request.form['description']
new_item = Item(name=name, description=description)
db.session.add(new_item)
db.session.commit()
return redirect(url_for('index'))
@app.route('/delete/<int:id>')
def delete_item(id):
item = Item.query.get_or_404(id)
db.session.delete(item)
db.session.commit()
return redirect(url_for('index'))
if __name__ == '__main__':
if not os.path.exists('instance/app.db'):
db.create_all()
app.run(debug=True)
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:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask SQLite App</title>
</head>
<body>
<h1>Item List</h1>
<ul>
{% for item in items %}
<li>
{{ item.name }}: {{ item.description }}
<a href="{{ url_for('delete_item', id=item.id) }}">Delete</a>
</li>
{% endfor %}
</ul>
<h2>Add New Item</h2>
<form action="{{ url_for('add_item') }}" method="POST">
<input type="text" name="name" placeholder="Item Name" required>
<input type="text" name="description" placeholder="Item Description" required>
<button type="submit">Add Item</button>
</form>
</body>
</html>
Running the Application
Start your Flask application:
python app.py
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