I have few projects that need to be connected with database (Postgres/MySQL). These projects requires basic CRUD operations. For now I create class called DataBaseManager and add class methods in it. In each method I open session, do my stuff and then close session. Session opens with previously declared engine. The reason I packed methods in DataBaseManager – I use this class to call database methods in my project.
So the question:
Is this method okay? Maybe there is another proper method for querying database with less memory and so on? Or maybe it’s good method? I want to improve my code and skills so I’m interesting is this okay?
Code looks something like that.
from sqlalchemy import create_engine, select, update, insert, delete, func, or_
from sqlalchemy.orm import Session
from models import User
USERNAME = 'DB_UN'
DBNAME = 'DB_NAME'
PASSWORD = 'DB_Password'
HOSTNAME = 'hostname'
engine = create_engine(f"postgresql+psycopg2://{USERNAME}:{PASSWORD}@{HOSTNAME}/{DBNAME}",
pool_recycle=3600, echo=True)
class DataBaseManager:
@classmethod
def get_all_users(cls, status) -> list:
session = Session(engine)
with session:
users = session.execute(select(User).where(User.status == status)).scalars()
return [user.id for user in users]
@classmethod
def update_last_activity(cls, id, date) -> None:
session = Session(engine)
with session:
session.execute(update(User).where(User.id == id).values(last_active_date=date))
session.commit()