src.utils package

Submodules

src.utils.database module

This module provides the Database class for managing database connections and sessions.

class src.utils.database.Database(sqlite_path: str | None = None, host: str | None = None, db_name: str | None = None, db_user: str | None = None, db_pass: str | None = None)

Bases: object

The Database class provides an interface for connecting to and interacting with a database.

It supports both SQLite and MySQL databases, allowing for flexible configuration through direct parameters or environment variables. The class also supports a testing mode using pytest, enabling the use of an in-memory SQLite database.

db_path

The database connection string.

Type:

str

connection

Indicates whether a connection to the database has been established.

Type:

bool

pytest_enabled

Indicates whether pytest is enabled. If env PYTEST is set to true, this will be True.

Type:

bool

engine

The SQLAlchemy engine object for the database connection.

Type:

Engine | None

__init__(

sqlite_path: str | None = None, host: str | None = None, db_name: str | None = None, db_user: str | None = None, db_pass: str | None = None

) -> None

Initializes the Database class.

connect() Database

Establishes a connection to the database.

session() Generator[Session, None, None]

Provides a context manager for database sessions.

close() None

Closes the database connection.

__del__() None

Closes the database connection when the object is deleted.

close() None

Close the database connection.

connect() Database

Connect to the database.

This function generates
  • engine: The SQLAlchemy engine object for the database connection.

Returns:

The Database object itself.

Return type:

Database

Raises:

SQLAlchemyError – If there is an error connecting to the database.

connection = False
db_path = ''
engine: Engine | None = None
session() Generator[Session, None, None]

Create a new session for the database connection.

This function generate
  • session: The SQLAlchemy session object for the database connection.

Example

```python db = Database().connect() with db.session() as session:

session.query(User).all()

```

Yields:

Session – The SQLAlchemy session object.

Raises:
  • ValueError – If the database connection is not established.

  • SQLAlchemyError – If there is an error during the session.

Module contents

This module provides utility functions and classes for the application.