-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
108 lines (88 loc) · 3.06 KB
/
Copy pathmain.py
File metadata and controls
108 lines (88 loc) · 3.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
from __future__ import annotations
# Standard library imports
import logging
from contextlib import asynccontextmanager
from typing import AsyncGenerator
# Third-party imports
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# First-party imports
from fmanagement.api.dependencies import (
close_mongodb_connection,
get_app_config,
get_s3_client,
set_connection_manager,
setup_logging,
)
from fmanagement.api.exception_handlers import register_exception_handlers
from fmanagement.api.v1.auth import router as auth_router
from fmanagement.api.v1.files import router as files_router
from fmanagement.storage.db.connection import MongoDBConnectionManager
from fmanagement.storage.enums import MongoDBCollections
from fmanagement.storage.repositories.users import UserRepository
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncGenerator[None, None]:
"""Manage application startup and shutdown.
Yields:
AsyncGenerator[None, None]: An async context manager that performs startup tasks before yielding.
Notes:
On startup, configures logging, connects to MongoDB, ensures the user
index and the S3 bucket exist. On shutdown, closes the MongoDB pool.
"""
setup_logging("conf/logger.yaml")
logger = logging.getLogger("fmanagement")
logger.info("Application starting up")
config = get_app_config()
manager = MongoDBConnectionManager(config=config.mongodb)
await manager.connect()
set_connection_manager(manager)
try:
users = UserRepository(
collection=manager.get_database()[MongoDBCollections.USERS]
)
await users.ensure_indexes()
except Exception as exc: # pylint: disable=broad-exception-caught
logger.error("Failed to ensure user indexes: %s", exc)
try:
await get_s3_client().ensure_bucket()
except Exception as exc: # pylint: disable=broad-exception-caught
logger.error("Failed to ensure S3 bucket: %s", exc)
yield
logger.info("Application shutting down")
await close_mongodb_connection()
logger.info("Shutdown complete")
config = get_app_config()
app = FastAPI(
title="fmanagement",
description="File storage service: upload, list, download and delete user-owned files.",
version="1.0.0",
docs_url="/docs",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=config.app.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
register_exception_handlers(app)
app.include_router(auth_router)
app.include_router(files_router)
def main() -> None:
"""Run the FastAPI application via uvicorn.
Notes:
Used only by ``python main.py``. The production container instead
invokes ``docker-entrypoint.sh``, which runs uvicorn directly
against the ``app`` symbol in this module.
"""
uvicorn.run(
"main:app",
host=config.app.host,
port=config.app.port,
reload=False,
log_level="info",
)
if __name__ == "__main__":
main()