1- from fastapi import APIRouter
1+ import inspect
2+ from fastapi import APIRouter , Depends
23
34OPEN_API_TAGS = []
45__app_controllers__ = []
@@ -32,7 +33,8 @@ class Controller():
3233
3334 It expose some utilities and decorator functions to define a router controller class
3435 '''
35- router : APIRouter
36+ RC_KEY = '__router__'
37+ SIGNATURE_KEY = '__signature__'
3638
3739 def __init__ (self , router : APIRouter , openapi_tag : dict = None ) -> None :
3840 '''
@@ -63,7 +65,8 @@ def resource(self):
6365 A decorator function to mark a Class as a Controller
6466 '''
6567 def wrapper (cls ):
66- if hasattr (cls , '__router__' ):
68+ # check if cls was extended from another Controller
69+ if hasattr (cls , Controller .RC_KEY ):
6770 self .__get_parent_routes (cls .__router__ )
6871
6972 cls .__router__ = self .router
@@ -87,12 +90,20 @@ def __parse_controller_router(controller):
8790 '''
8891 Private utility to parse the router controller property and extract the correct functions handlers
8992 '''
90- for route in controller .__router__ .routes :
91- func = route .endpoint
92- if hasattr (func , '__get__' ):
93- route .endpoint = func .__get__ (controller , controller .__class__ )
93+ router = getattr (controller , Controller .RC_KEY )
94+
95+ for route in router .routes :
96+ # get the signature of the endpoint function
97+ signature = inspect .signature (route .endpoint )
98+ # get the parameters of the endpoint function
99+ signature_parameters = list (signature .parameters .values ())
100+
101+ # replace the class instance with the itself FastApi Dependecy
102+ signature_parameters [0 ] = signature_parameters [0 ].replace (default = Depends (controller .__class__ ))
103+ new_signature = signature .replace (parameters = signature_parameters )
104+ setattr (route .endpoint , Controller .SIGNATURE_KEY , new_signature )
94105
95- return controller . __router__
106+ return router
96107
97108 @staticmethod
98109 def routers ():
0 commit comments