You are on page 1of 16

SQLAlchemy

Connecting Flask application to SQLITE db

Zhantileuov Eldiyar, 2022


Set up environment
Task 1.

I. First create project and install flask. Please follow instruction from official documentation.

II. If you want to install globally:

- pip install flask-sqlalchemy and pip install Flask (if pip doesn’t found use pip3)

II. Open your project from PyCharm or any other IDE


Set up environment

I.In folder <your project> create .py file.


Connecting to DataBase

I. The only required Flask app config is the


SQLALCHEMY_DATABASE_URI key. That is a connection string
that tells SQLAlchemy what database to connect to.

II. Subclass db.Model to define a model class. The db


object makes the names in sqlalchemy and
sqlalchemy.orm available for convenience, such as
db.Column. The model will generate a table name by
converting the CamelCase class name to snake_case.

III.After all models and tables are defined, call


SQLAlchemy.create_all() to create the table schema in
the database. This requires an application context. Since
you’re not in a request at this point, create one manually.
Insert data
Update data
Update data
Update data
One to Many relationship
One to Many
One To Manyrelationship
Many
One to Many relationship
Many To Many

I. Many to Many relationship between two tables is achieved by adding an association table such that
it has two foreign keys - one from each table’s primary key. Moreover, classes mapping to the two
tables have an attribute with a collection of objects of other association tables assigned as secondary
attribute of relationship() function.

https://michaelcho.me/article/many-to-many-relationships-in-sqlalchemy-models-flask
useful links

I. CRUD Operations https://flaskage.readthedocs.io/en/latest/database_queries.html

II.Flask SQLAlchemy https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/

III. https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/

IV. https://www.youtube.com/playlist?list=PLXmMXHVSvS-BlLA5beNJojJLlpE0PJgCW

You might also like