Coverage for mpcforces_extractor\api\routes\database.py: 46%
26 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-07 23:06 +0100
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-07 23:06 +0100
1import os
2from fastapi.templating import Jinja2Templates
3from fastapi import APIRouter, HTTPException, Request
4from mpcforces_extractor.api.config import UPLOAD_FOLDER, TEMPLATES_DIR
5from mpcforces_extractor.api.db.database import MPCDatabase
6from mpcforces_extractor.api.db.schemas import DatabaseRequest
8templates = Jinja2Templates(directory=TEMPLATES_DIR)
9router = APIRouter()
12@router.post("/import-db")
13async def import_db(request: Request, db_request: DatabaseRequest):
14 """
15 Import a database (db) file and reinitialize the database
16 """
17 # Get the uploaded file
18 db_file = db_request.database_filename
20 db_path = str(UPLOAD_FOLDER) + os.sep + db_file
22 # Check if the file exists
23 if not os.path.exists(db_path):
24 raise HTTPException(
25 status_code=404, detail=f"Database file {db_file} not found"
26 )
28 app = request.app
30 # Reinitialize the database
31 if not hasattr(app, "db"):
32 app.db = MPCDatabase(db_path)
33 app.db.reinitialize_db(db_path)
34 return {"message": "Database imported successfully!"}
37@router.post("/disconnect-db")
38async def disconnect_db(request: Request):
39 """
40 Closes the database connection, for the file to be deleted
41 """
42 app = request.app
43 if hasattr(app, "db"):
44 app.db.close()
45 del app.db
46 return {"message": "Database disconnected successfully!"}