Skip to content

Commit

Permalink
feat: implement dependency injection for file processing and refactor…
Browse files Browse the repository at this point in the history
… upload endpoint (#35)

Introduce dependency injection for the file processing service, refactor
the upload endpoint to utilize this service, and clean up obsolete code
and import paths.
  • Loading branch information
0x1026 authored Feb 18, 2025
2 parents 7c580fa + efd0875 commit fc3d68c
Show file tree
Hide file tree
Showing 7 changed files with 70 additions and 60 deletions.
61 changes: 16 additions & 45 deletions src/api/v1/endpoints/sensors.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,35 @@
import io
import os
import time
import shutil
from fastapi import APIRouter, HTTPException, Query, Request, status
from fastapi import APIRouter, HTTPException, Query, Request, status, Depends
from injector import Injector, inject
from src.service.file_service import MAX_FILE_SIZE, FileService

router = APIRouter()

MAX_FILE_SIZE = 1024 * 1024
DIR = "saved_files"
ALLOWED_EXTENSIONS = [".txt", ".json", ".csv"]

async def process_up(content: str, extension: str):
print("Procesando evento 'up'")

timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
def get_file_service(request: Request) -> FileService:
injector: Injector = request.app.state.injector
return injector.get(FileService)

filename = f"{timestamp}{extension}"
os.makedirs(DIR, exist_ok=True)
file_location = os.path.join(DIR, filename)


with open(file_location, "wb+") as f:
shutil.copyfileobj(content, f)

print(f"file saved: {file_location}")

async def process_join(content: str):
pass

@router.post("/uploadFile")
async def create_upload_file(
request: Request,
event: str = Query(..., description="Tipo de evento. Ejemplo: 'up' o 'join'")
event: str = Query(...,
description="Tipo de evento. Ejemplo: 'up' o 'join'"),
file_service: FileService = Depends(get_file_service)
):
body = await request.body()

if (len(body) > MAX_FILE_SIZE):
raise HTTPException(
detail="File too large",
status_code=403
)

content = io.BytesIO(body)

timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
extension = ".json"
filename = f"{timestamp}{extension}"
os.makedirs(DIR, exist_ok=True)
file_location = os.path.join(DIR, filename)

with open(file_location, "wb") as f:
f.write(content.getvalue())
if len(body) > MAX_FILE_SIZE:
raise HTTPException(detail="File too large", status_code=403)

content.seek(0)
extension = ".json"

if event == "up":
await process_up(content, extension)
file_service.process_up(body, extension)
elif event == "join":
await process_join(content)
file_service.process_join(body)
else:
raise HTTPException(status_code=400, detail=f"Evento {event} no implementado")
raise HTTPException(
status_code=400, detail=f"Evento {event} no implementado")

return status.HTTP_200_OK
Empty file added src/core/__init__.py
Empty file.
1 change: 1 addition & 0 deletions src/core/db/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
load_dotenv()
engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))


def get_session():
with Session(engine) as session:
yield session
17 changes: 17 additions & 0 deletions src/core/di.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# src/core/di.py
from injector import Module, provider, singleton
from sqlmodel import Session
from src.service.file_service import FileService
from src.core.db.connection import engine


class AppModule(Module):
@singleton
@provider
def provide_session(self) -> Session:
return Session(engine)

@singleton
@provider
def provide_file_service(self, session: Session) -> FileService:
return FileService(session)
7 changes: 7 additions & 0 deletions src/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from src.api.v1.endpoints import sensors
from injector import Injector
from src.core.di import AppModule


def create_app() -> FastAPI:
app = FastAPI()
Expand All @@ -11,6 +14,10 @@ def create_app() -> FastAPI:
allow_methods=["*"],
allow_headers=["*"],
)

injector = Injector([AppModule()])
app.state.injector = injector

app.include_router(sensors.router)
return app

Expand Down
29 changes: 29 additions & 0 deletions src/service/file_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import os
import time
from sqlmodel import Session

DIR = "saved_files"
MAX_FILE_SIZE = 1024 * 1024
ALLOWED_EXTENSIONS = [".txt", ".json", ".csv"]


class FileService:
def __init__(self, session: Session):
self.session = session

def save_file(self, content: bytes, extension: str) -> str:
timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
filename = f"{timestamp}{extension}"
os.makedirs(DIR, exist_ok=True)
file_location = os.path.join(DIR, filename)

with open(file_location, "wb") as f:
f.write(content)

return file_location

def process_up(self, content: bytes, extension: str):
file_location = self.save_file(content, extension)

def process_join(self, content: bytes):
pass
15 changes: 0 additions & 15 deletions tests/unit/test_db.py

This file was deleted.

0 comments on commit fc3d68c

Please sign in to comment.