Skip to content

Database Connection

Spera Alfredo Jeshoua edited this page May 14, 2025 · 5 revisions

VM Lab Project Structure Badge

Overview

Manages database sessions and CRUD operations via functions. These are in the file backend/database.py.

Prerequisites

  • The database must be configured and working.

  • The .streamlit/secrets.toml file must be configured with all the necessary data and credentials to access the database.

Libraries

This project utilizes the following tools for database management:

  • psycopg2: A PostgreSQL adapter for Python.
  • SQLAlchemy: An ORM (Object-Relational Mapping) library for managing and interacting with database tables in Python.

How does it work?

  1. On the server startup, it reads database credentials (username, password, address, port, and name) from .streamlit/secrets.toml and constructs the database URL for a PostgreSQL database.
  2. Sets up a SQLAlchemy engine and the session factory.
  3. Loads initial users from first_users.yaml if the database is empty. It automatically hashes their passwords, and adds them to the database.

API

Database Connection

To perform database queries, you must first obtain a database session using the get_db() context manager function from backend/database.py.

Note

The get_db() function is a generator that yields a database session object. It should be used within a with statement to ensure proper resource management.

Most functions that execute a database query require that a database session object must be passed as an argument.

with get_db() as db:
    # Execute your database query here

Generic add and delete functions

This file provides two generic functions:

  • add_to_db(): Adds a User, VirtualMachine, or Bookmark object to the database, commits the transaction, and refreshes the object.
  • delete_from_db(): Removes a User, VirtualMachine, or Bookmark object from the database and commits the change.
with get_db() as db:
    refreshed_VM = add_to_db(db, my_vm)
    
    delete_from_db(db, refreshed_VM)

Clone this wiki locally