SQLAlchemy setup

Installation

  • To install run

pip3 install sqlalchemy
pip3 install psycopg

Note: SQLAlchemy has all the code needed for us to interact with the database and write python code to do so, but it does not know how to communicate with the Database itself.

  • Having said that, we would need to install the driver separately

  • In our Postgres case that would be psycopg

  • Usually all ORMs work like this where you need the driver separately

File Structure

.
└── sql_app
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ crud.py
    β”œβ”€β”€ database.py
    β”œβ”€β”€ main.py
    β”œβ”€β”€ models.py
    └── schemas.py

Guidelines

  • Once installed we will create a file called database.py in our App folder

  • This file will handle our database connection

  • In this file we will have the following:

  • Now that this is set up, we will create a new file called models.py

  • This is where all our database tables will be created

  • Each model is a table

  • The file contains the following:

  • Now that this is created we will need to set up the following line in the main.py file

  • Now this should be good to go

  • Every time we will interact with the database we will get a session

  • Once we are done interacting, the session will close

  • We can start setting up paths to our App using this code

  • By setting all of this up, SQLAlchemy will connect to the Database

  • Check if the tables exist

  • If they don't it will create them

  • If they do it will mode on

  • But now if we connect to the database we should see the table created from scratch

Cleanup

  • Just to keep everything clean, we will move the dependency code in our database.py file

  • This keeps everything clean, all the database stuff with the database stuff

  • Additionally we will have to import this in our main.py file

database.py

main.py

Last updated