Skip to content

Commit

Permalink
issue #178: connection manager no longer needed
Browse files Browse the repository at this point in the history
  • Loading branch information
k-allagbe committed Nov 4, 2024
1 parent 8237eff commit b5bd1c4
Show file tree
Hide file tree
Showing 10 changed files with 112 additions and 350 deletions.
5 changes: 1 addition & 4 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
from pydantic import Field, PostgresDsn
from pydantic_settings import BaseSettings

from app.connection_manager import ConnectionManager

load_dotenv()


Expand Down Expand Up @@ -34,8 +32,7 @@ def configure(app: FastAPI, settings: Settings):
conninfo=settings.fertiscan_db_url.unicode_string(),
kwargs={"options": f"-c search_path={settings.fertiscan_schema},public"},
)
connection_manager = ConnectionManager(pool, settings.testing.lower() == "true")
app.connection_manager = connection_manager
app.pool = pool

# Initialize OCR
ocr = OCR(api_endpoint=settings.api_endpoint, api_key=settings.api_key)
Expand Down
110 changes: 0 additions & 110 deletions app/connection_manager.py

This file was deleted.

20 changes: 10 additions & 10 deletions app/controllers/inspections.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,20 @@
from fertiscan.db.queries.inspection import (
InspectionNotFoundError as DBInspectionNotFoundError,
)
from psycopg_pool import ConnectionPool

from app.connection_manager import ConnectionManager
from app.exceptions import InspectionNotFoundError, MissingUserAttributeError, log_error
from app.models.inspections import Inspection, InspectionData
from app.models.label_data import LabelData
from app.models.users import User


async def read_all(cm: ConnectionManager, user: User):
async def read_all(cp: ConnectionPool, user: User):
"""
Retrieves all inspections associated with a user, both verified and unverified.
Args:
cm (ConnectionManager): An instance managing the database connection.
cp (ConnectionPool): The connection pool to manage database connections.
user (User): User instance containing user details, including the user ID.
Returns:
Expand All @@ -37,7 +37,7 @@ async def read_all(cm: ConnectionManager, user: User):
if not user.id:
raise MissingUserAttributeError("User ID is required for fetching inspections.")

with cm, cm.get_cursor() as cursor:
with cp.connection() as conn, conn.cursor() as cursor:
inspections = await asyncio.gather(
get_user_analysis_by_verified(cursor, user.id, True),
get_user_analysis_by_verified(cursor, user.id, False),
Expand All @@ -64,12 +64,12 @@ async def read_all(cm: ConnectionManager, user: User):
return inspections


async def read(cm: ConnectionManager, user: User, id: UUID | str):
async def read(cp: ConnectionPool, user: User, id: UUID | str):
"""
Retrieves a specific inspection associated with a user by inspection ID.
Args:
cm (ConnectionManager): An instance managing the database connection.
cp (ConnectionPool): The connection pool to manage database connections.
user (User): User instance containing user details, including the user ID.
id (UUID | str): Unique identifier of the inspection, as a UUID or a string convertible to UUID.
Expand All @@ -90,7 +90,7 @@ async def read(cm: ConnectionManager, user: User, id: UUID | str):
if not isinstance(id, UUID):
id = UUID(id)

with cm, cm.get_cursor() as cursor:
with cp.connection() as conn, conn.cursor() as cursor:
try:
inspection = await get_full_inspection_json(cursor, id, user.id)
except DBInspectionNotFoundError as e:
Expand All @@ -100,7 +100,7 @@ async def read(cm: ConnectionManager, user: User, id: UUID | str):


async def create(
cm: ConnectionManager,
cp: ConnectionPool,
user: User,
label_data: LabelData,
label_images: list[bytes],
Expand All @@ -110,7 +110,7 @@ async def create(
Creates a new inspection record associated with a user.
Args:
cm (ConnectionManager): An instance managing the database connection.
cp (ConnectionPool): The connection pool to manage database connections.
user (User): User instance containing user details, including the user ID.
label_data (LabelData): Data model containing label information required for the inspection.
label_images (list[bytes]): List of images (in byte format) to be associated with the inspection.
Expand All @@ -125,7 +125,7 @@ async def create(
if not user.id:
raise MissingUserAttributeError("User ID is required for creating inspections.")

with cm, cm.get_cursor() as cursor:
with cp.connection() as conn, conn.cursor() as cursor:
container_client = ContainerClient.from_connection_string(
connection_string, container_name=f"user-{user.id}"
)
Expand Down
16 changes: 8 additions & 8 deletions app/controllers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from datastore import get_user, new_user
from datastore.db.queries.user import UserNotFoundError as DBUserNotFoundError
from fastapi.logger import logger
from psycopg_pool import ConnectionPool

from app.connection_manager import ConnectionManager
from app.exceptions import (
MissingUserAttributeError,
UserConflictError,
Expand All @@ -13,14 +13,14 @@
from app.models.users import User


async def sign_up(cm: ConnectionManager, user: User, connection_string: str) -> User:
async def sign_up(cp: ConnectionPool, user: User, connection_string: str) -> User:
"""
Registers a new user in the system.
Args:
cm (ConnectionManager): An instance managing the database connection.
cp (ConnectionPool): The connection pool to manage database connections.
user (User): The User instance containing the user's details.
connection_string (str): Connection string for database setup.
connection_string (str): The database connection string for setup.
Raises:
MissingUserAttributeError: Raised if the username is not provided.
Expand All @@ -33,7 +33,7 @@ async def sign_up(cm: ConnectionManager, user: User, connection_string: str) ->
raise MissingUserAttributeError("Username is required for sign-up.")

try:
with cm, cm.get_cursor() as cursor:
with cp.connection() as conn, conn.cursor() as cursor:
logger.debug(f"Creating user: {user.username}")
user_db = await new_user(cursor, user.username, connection_string)
except DBUserAlreadyExistsError as e:
Expand All @@ -43,12 +43,12 @@ async def sign_up(cm: ConnectionManager, user: User, connection_string: str) ->
return user.model_copy(update={"id": user_db.id})


async def sign_in(cm: ConnectionManager, user: User) -> User:
async def sign_in(cp: ConnectionPool, user: User) -> User:
"""
Authenticates an existing user in the system.
Args:
cm (ConnectionManager): An instance managing the database connection.
cp (ConnectionPool): The connection pool to manage database connections.
user (User): The User instance containing the user's details.
Raises:
Expand All @@ -62,7 +62,7 @@ async def sign_in(cm: ConnectionManager, user: User) -> User:
raise MissingUserAttributeError("Username is required for sign-in.")

try:
with cm, cm.get_cursor() as cursor:
with cp.connection() as conn, conn.cursor() as cursor:
logger.debug(f"Fetching user ID for username: {user.username}")
user_db = await get_user(cursor, user.username)
except DBUserNotFoundError as e:
Expand Down
13 changes: 7 additions & 6 deletions app/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
from fastapi import Depends, File, HTTPException, Request, UploadFile
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pipeline import GPT, OCR
from psycopg_pool import ConnectionPool

from app.config import Settings
from app.connection_manager import ConnectionManager

from app.controllers.users import sign_in
from app.exceptions import UserNotFoundError
from app.models.users import User
Expand All @@ -19,11 +20,11 @@ def get_settings():
return Settings()


def get_connection_manager(request: Request) -> ConnectionManager:
def get_connection_pool(request: Request) -> ConnectionPool:
"""
Returns the app's ConnectionManager instance.
Returns the app's connection pool.
"""
return request.app.connection_manager
return request.app.pool


def get_ocr(request: Request) -> OCR:
Expand Down Expand Up @@ -54,13 +55,13 @@ def authenticate_user(credentials: HTTPBasicCredentials = Depends(auth)):

async def fetch_user(
auth_user: User = Depends(authenticate_user),
cm: ConnectionManager = Depends(get_connection_manager),
cp: ConnectionPool = Depends(get_connection_pool),
) -> User:
"""
Fetches the authenticated user's info from db.
"""
try:
return await sign_in(cm, auth_user)
return await sign_in(cp, auth_user)
except UserNotFoundError:
raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED, detail="Invalid username or password"
Expand Down
Loading

0 comments on commit b5bd1c4

Please sign in to comment.