This project demonstrates the implementation of the Virtual Proxy Pattern (Lazy Initialization) in Python, using SQLAlchemy to simulate database access (PostgreSQL).
The main goal is to control the loading of a high-cost domain object (ClientORM) only at the moment it is truly needed, improving performance.
The source code is isolated within the app/ package structure, following standard Python packaging practices.
/proxy-project
βββ .env # PostgreSQL connection environment variables
βββ requirements.txt # Project dependencies
βββ app/ # Main Python Package
βββ client.py # Application Entry Point (GUI and Console Demo)
βββ init_db.py # Creates the Clients and Orders tables
βββ cleanup_db.py # **NEW:** Removes all tables (required for full reset)
βββ seed_db.py # **NEW:** Populates the DB with 1000 test clients
βββ src/
βββ core/ # Domain Logic (Proxy, ORM Models)
β βββ client_proxy.py # The Virtual Proxy implementation
β βββ clientORM.py # The Real Subject (SQLAlchemy Model)
β βββ model.py # Database Configuration (Engine, Session)
β βββ order.py # Order Data Model
βββ gui/ # Presentation Layer (Tkinter App)
βββ client_gui.py
Ensure you have Python 3.8+ installed and a PostgreSQL server running locally (default port 5432).
Create or update the .env file inside the app/ directory (/proxy-project/app/.env) with your database credentials:
# .env content example
DB_HOST=localhost
DB_PORT=5432
DB_NAME=futino
DB_USER=postgres
DB_PASSWORD=supra
DB_DRIVER=psycopg2Install the necessary libraries using requirements.txt:
pip install -r requirements.txtAll scripts must be executed from the project root directory (/proxy-project/) using Python's module notation (python -m).
Before running the application, you must create the tables and insert the test data (1000 clients and 2000 orders).
| Command | Description |
|---|---|
python -m app.init_db |
Creates the clients and orders tables in the database. |
python -m app.seed_db |
Inserts 1000 clients and 2000 orders (test data). (Requires empty tables!) |
Data Cleanup (Required after "UniqueViolation" errors)
If you need to re-run seed_db after a duplicate key error, clear the tables using:
python -m app.cleanup_db
python -m app.init_db
python -m app.seed_dbExecute the main entry point, which loads the graphical interface (ClientApp / Tkinter):
python -m app.clientWhen interacting with the GUI, observe the log (bottom part of the window) to see when the Proxy is:
- Lazy Initializing: Loading the
ClientORMobject from the database (only when you click "Access Name"). - Lazy Loading: Fetching the list of orders via SQLAlchemy (only when you click "Access Orders").