Seventh Installation of Flask Tutorial Series: Explored Databases and SQLAlchemy

Posted by


In this tutorial, we will be discussing databases and how to use SQLAlchemy with Flask. SQLAlchemy is a powerful Python library for working with databases, and it provides a high-level API for interacting with databases in a more Pythonic way. In this tutorial series, we will focus on using SQLAlchemy with Flask, a popular web framework for building web applications in Python.

Before we dive into using SQLAlchemy with Flask, let’s first understand the basics of databases. A database is an organized collection of data, typically stored and accessed electronically from a computer system. Databases can be relational or non-relational, but for this tutorial, we will be focusing on relational databases.

A relational database is a type of database that stores and provides access to data points that are related to one another. These data points are organized into tables, which consist of rows and columns. Each row in a table represents a record, and each column represents a field or an attribute of the record. In relational databases, tables can be related to one another through keys, such as primary keys and foreign keys.

Now, let’s talk about SQLAlchemy. SQLAlchemy is an Object-Relational Mapping (ORM) library for Python that provides a high-level abstraction for interacting with databases. With SQLAlchemy, you can work with databases using Python objects and methods, rather than writing SQL queries directly. SQLAlchemy supports a wide variety of database systems, including SQLite, MySQL, PostgreSQL, and more.

In this tutorial series, we will be using SQLite as our database system, as it is lightweight and easy to setup for development purposes. SQLite is a self-contained, serverless, zero-configuration database engine that is widely used in web applications for storing data locally.

To get started with using SQLAlchemy with Flask, you will first need to install the required dependencies. You can do this by running the following command:

pip install Flask SQLAlchemy

Next, let’s create a new Flask project and set up our database using SQLAlchemy. Create a new Python file, for example 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:///db.sqlite'
db = SQLAlchemy(app)

if __name__ == '__main__':
    app.run()

In this code snippet, we first import the required libraries – Flask and SQLAlchemy. We then create a new Flask app instance and configure the database URI to point to a SQLite database file called db.sqlite. Next, we create a new SQLAlchemy instance and pass in the Flask app object to bind them together.

You can now create your database models by defining Python classes that represent tables in your database. For example, let’s create a simple User model to store user information:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return f'<User {self.username}>'

In this User model, we defined a table with three columns – id, username, and email. The id column is the primary key, which uniquely identifies each user record. The username and email columns are defined as string fields with specific length constraints.

To create the initial database schema, you can run the following commands in a Python shell:

from app import db
db.create_all()

This will create the necessary tables in the SQLite database file db.sqlite based on the models you have defined. You can now interact with the database using SQLAlchemy methods such as db.session.add(), db.session.commit(), db.session.query(), and so on.

For example, to add a new user to the database, you can do the following:

from app import db, User

new_user = User(username='john_doe', email='john.doe@example.com')
db.session.add(new_user)
db.session.commit()

To query all users from the database, you can do the following:

from app import db, User

users = User.query.all()
for user in users:
    print(user.username, user.email)

In this tutorial series, we have covered the basics of databases, SQLAlchemy, and how to use SQLAlchemy with Flask to interact with a SQLite database. You can now expand on this knowledge by exploring more advanced features of SQLAlchemy, such as relationships between tables, queries, and more. SQLAlchemy provides a rich set of features for working with databases, and it is a powerful tool for building web applications with Flask.

0 0 votes
Article Rating

Leave a Reply

20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@pawjast
2 hours ago

In 12:49 you run `flask db init`.

It works but is a bit confusing (unless it's explained further in the video).

How does Flask know where to look for a `db` to initiate?

I think it only works because we defined our app inside `app.py` which is sort of a convention so this is a default place for an app to be in.

So Flask checks `app.py` by default – finds the `db` in it and all is good.

But if you change the name to anything, e.g. `my_app.py` – then the `flask db init` throws an error ("Error: Could not locate a Flask application.")

So first you need to tell Flask where your actual `app` and `db` is by setting `FLASK_APP` variable or calling `flask –app my_app:app` where:
– `my_app` is the name of the file you're app is in (so `my_app.py`)
– `app` is the name of the variable the Flask app was assigned to inside that file (in the tutorial we actually use `flask_app` inside `run.py`)

@masteradvisor594
2 hours ago

15:40

@spaff_hazz
2 hours ago

after sending a post request, if i reload the page, i get the form resubmission alert and if i continue it takes the data that i last filled the form with even though it's not in the input field. how do i prevent this?

@gerlannoharrisson9210
2 hours ago

top! thank you bro!

@mugomuiruri2313
2 hours ago

good see u again

@leonardomoreiralouzas3995
2 hours ago

Relly good! I changed the detail and delete to a single view to make it less code, I think it looks better that way. All the code is in my github repo

@saulvera5469
2 hours ago

dont know why but when I try to migrate it doesn't add any table, I ended up creating it in SQL

@mhmmdalfatehhishahmuddin2670
2 hours ago

My problem is when migrating SQL when I run the command: flask db init it say 'Could not import 'db'. How to fix it?

@masoooomx
2 hours ago

which OS and which IDE ????

@samannwaysil4412
2 hours ago

Keep these tutorials coming brother!

@kylec.5476
2 hours ago

Great series!

@michaelrobson3092
2 hours ago

Awesome , could you show how we could use a DB like Redis with SQLite & SQLAlchemy

@cvicvicvi
2 hours ago

Hey, thank you so much for this tutorial series, it's very well thought and easy to understand for beginners like me. Currently trying to develop my first web app, that's exactly what I needed.

@FrozenShield
2 hours ago

Thanks for the tutorial, it helped me understand flask-sqlalchmey! I am trying to understand at 15:10 you mentioned that it loops from the other python files. Is it necessary to loop it like that? I also looked at the quick start instructions for flask-sqlalchemy and it looks like you can do it all in app.py. When you write flask run in the terminal it looks for app.py to run that so is it best practice to keep everything in app.py or split it out like how you did it?

@jayewastaken9486
2 hours ago

I love this series!

@wonkywombat
2 hours ago

Great episode. I too will need to redo this with an existing MySQL db.

@RocketLR
2 hours ago

my problem is with the db.Model classes is that the _init_ does not do anything when creating a object from those classes..
So i have to make classes that inherit from Base. But then they dont get created as far as i can tell..
As im writing this, im wodnering if should create a db.Model table then another class that inherins from that class that inherited from db.Model..

@johnraz99
2 hours ago

Thank You. I just need to get it to work with my MySQL database now!

@aafan.kuware
2 hours ago

27:56 was not htmx will be the best choice to do this crud operations instead of writing these long JS?

if possible, please make one separate video and all futher operation with HTMX.

@eklownr4566
2 hours ago

Nice tutorial.

20
0
Would love your thoughts, please comment.x
()
x