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.
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.
First, let's set up a new Flask project and connect it to an SQLite database.
pip install flask flask-sqlalchemyNow, create a new file called app.py and add the following code:
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.
Creating a table in SQLite is as simple as writing a Python class that inherits from db.Model. Let's create a User table:
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.
Now that we have a User table, let's learn how to add, read, update, and delete data using SQLite.
To add a new user, we'll use the add_user() function:
def add_user(username, email):
user = User(username=username, email=email)
db.session.add(user)
db.session.commit()To read user data, we'll use the get_user_by_username() function:
def get_user_by_username(username):
return User.query.filter_by(username=username).first()To update a user, we'll use the update_user() function:
def update_user(user, new_email):
user.email = new_email
db.session.commit()To delete a user, we'll use the delete_user() function:
def delete_user(user):
db.session.delete(user)
db.session.commit()What does the `db.create_all()` function do?
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! 💡