1- from  fastapi  import  FastAPI , Request 
2- from  fastapi .exception_handlers  import  (
3-     http_exception_handler ,
4-     request_validation_exception_handler ,
5- )
1+ from  contextlib  import  asynccontextmanager 
2+ from  typing  import  Any 
3+ 
4+ from  fastapi  import  FastAPI 
65from  fastapi .exceptions  import  RequestValidationError 
76from  starlette .exceptions  import  HTTPException 
87from  starlette .middleware .cors  import  CORSMiddleware 
9- from  starlette .responses  import  Response 
108
9+ from  app .exception_handlers  import  (
10+     http_exception_handler ,
11+     request_validation_exception_handler ,
12+     unhandled_exception_handler ,
13+ )
14+ from  app .middleware  import  log_request_middleware 
1115from  app .router  import  api_router 
1216from  app .services .populate_service  import  students_bulkwrite 
1317
2529[Motor](https://motor.readthedocs.io/en/stable/): Asynchronous Python driver for MongoDB. 
2630''' 
2731
32+ @asynccontextmanager  
33+ async  def  lifespan (app : FastAPI ) ->  Any :
34+     await  students_bulkwrite ()
35+     yield 
36+ 
2837app  =  FastAPI (
2938    title = "FastAPI/MongoDB Template" ,
3039    description = DESCRIPTION ,
31-     version = "1.4 .0" ,
40+     version = "1.5 .0" ,
3241    contact = {
3342        "name" : "Antonio Germán Márquez Trujillo" ,
3443        "url" : "https://github.com/GermanMT" ,
354436-     }
45+     },
46+     license_info = {
47+         "name" : "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)" ,
48+         "url" : "https://www.gnu.org/licenses/gpl-3.0.html" ,
49+     },
50+     lifespan = lifespan ,
3751)
3852
3953
40- @app .exception_handler (HTTPException ) 
41- async  def  custom_http_exception_handler (request : Request , exc : HTTPException ) ->  Response :
42-     return  await  http_exception_handler (request , exc )
43- 
44- 
45- @app .exception_handler (RequestValidationError ) 
46- async  def  validation_exception_handler (request : Request , exc : RequestValidationError ) ->  Response :
47-     return  await  request_validation_exception_handler (request , exc )
48- 
49- 
50- @app .on_event ("startup" ) 
51- async  def  startup_event () ->  None :
52-     await  students_bulkwrite ()
53- 
54- 
55- # Set all CORS enabled origins 
54+ app .middleware ("http" )(log_request_middleware )
5655app .add_middleware (
5756    CORSMiddleware ,
5857    allow_origins = [],
@@ -62,4 +61,9 @@ async def startup_event() -> None:
6261)
6362
6463
64+ app .add_exception_handler (RequestValidationError , request_validation_exception_handler )
65+ app .add_exception_handler (HTTPException , http_exception_handler )
66+ app .add_exception_handler (Exception , unhandled_exception_handler )
67+ 
68+ 
6569app .include_router (api_router )
0 commit comments