1818
1919import logging
2020from contextlib import AsyncExitStack , asynccontextmanager
21+ from functools import cache
2122from typing import TYPE_CHECKING , cast
2223from urllib .parse import urlsplit
2324
@@ -64,8 +65,9 @@ def get_cookie_path() -> str:
6465
6566log = logging .getLogger (__name__ )
6667
67- app : FastAPI | None = None
68- auth_manager : BaseAuthManager | None = None
68+
69+ class _AuthManagerState :
70+ instance : BaseAuthManager | None = None
6971
7072
7173@asynccontextmanager
@@ -117,19 +119,16 @@ def create_app(apps: str = "all") -> FastAPI:
117119 return app
118120
119121
122+ @cache
120123def cached_app (config = None , testing = False , apps = "all" ) -> FastAPI :
121124 """Return cached instance of Airflow API app."""
122- global app
123- if not app :
124- app = create_app (apps = apps )
125- return app
125+ return create_app (apps = apps )
126126
127127
128128def purge_cached_app () -> None :
129129 """Remove the cached version of the app and auth_manager in global state."""
130- global app , auth_manager
131- app = None
132- auth_manager = None
130+ cached_app .cache_clear ()
131+ _AuthManagerState .instance = None
133132
134133
135134def get_auth_manager_cls () -> type [BaseAuthManager ]:
@@ -150,10 +149,9 @@ def get_auth_manager_cls() -> type[BaseAuthManager]:
150149
151150def create_auth_manager () -> BaseAuthManager :
152151 """Create the auth manager."""
153- global auth_manager
154152 auth_manager_cls = get_auth_manager_cls ()
155- auth_manager = auth_manager_cls ()
156- return auth_manager
153+ _AuthManagerState . instance = auth_manager_cls ()
154+ return _AuthManagerState . instance
157155
158156
159157def init_auth_manager (app : FastAPI | None = None ) -> BaseAuthManager :
@@ -171,12 +169,12 @@ def init_auth_manager(app: FastAPI | None = None) -> BaseAuthManager:
171169
172170def get_auth_manager () -> BaseAuthManager :
173171 """Return the auth manager, provided it's been initialized before."""
174- if auth_manager is None :
172+ if _AuthManagerState . instance is None :
175173 raise RuntimeError (
176174 "Auth Manager has not been initialized yet. "
177175 "The `init_auth_manager` method needs to be called first."
178176 )
179- return auth_manager
177+ return _AuthManagerState . instance
180178
181179
182180def init_plugins (app : FastAPI ) -> None :
0 commit comments