SQLite in Flask: A Comprehensive Guide 🎯

beginner
15 min

SQLite in Flask: A Comprehensive Guide 🎯

Introduction 📝

Welcome to the SQLite in Flask tutorial! In this lesson, you'll learn how to use SQLite databases with Flask, a popular Python web framework. By the end of this tutorial, you'll have a solid understanding of why and how to use SQLite in your Flask projects.

What is SQLite? 💡

SQLite is a lightweight, easy-to-use, and file-based relational database management system. Unlike other databases that require separate installation, SQLite comes pre-installed with Python, making it a great choice for beginners and small projects.

Setting Up Flask with SQLite ✅

First, let's set up a new Flask project and connect it to an SQLite database.

bash
pip install flask flask-sqlalchemy

Now, create a new file called app.py and add the following code:

python
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db = SQLAlchemy(app) if __name__ == '__main__': db.create_all() app.run(debug=True)

In the code above, we've imported the necessary modules, created a Flask app, and configured it to use SQLite. We also defined a database URI (Uniform Resource Identifier) for our SQLite database file named site.db. When you run the app, the database will be created automatically.

Working with SQLite Tables 💡

Creating a table in SQLite is as simple as writing a Python class that inherits from db.Model. Let's create a User table:

python
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) def __repr__(self): return f'<User {self.username}>'

In the code above, we created a User class with three columns: id, username, and email. We also defined a __repr__() method to help print the user objects.

Adding, Reading, Updating, and Deleting (ARUD) Data 💡

Now that we have a User table, let's learn how to add, read, update, and delete data using SQLite.

Adding Data 💡

To add a new user, we'll use the add_user() function:

python
def add_user(username, email): user = User(username=username, email=email) db.session.add(user) db.session.commit()

Reading Data 💡

To read user data, we'll use the get_user_by_username() function:

python
def get_user_by_username(username): return User.query.filter_by(username=username).first()

Updating Data 💡

To update a user, we'll use the update_user() function:

python
def update_user(user, new_email): user.email = new_email db.session.commit()

Deleting Data 💡

To delete a user, we'll use the delete_user() function:

python
def delete_user(user): db.session.delete(user) db.session.commit()

Quiz 🎯

Quick Quiz
Question 1 of 1

What does the `db.create_all()` function do?

Conclusion 💡

Now you've learned the basics of using SQLite with Flask! You can build a simple CRUD (Create, Read, Update, Delete) application using the concepts you've learned in this tutorial.

Happy coding! 💡