Skip to content

Commit 21dae80

Browse files
vincbeckjscheffl
authored andcommitted
Remove global from FastAPI app.py (#59772) (#62997)
* Remove global from FastAPI app.py * Remove global from FastAPI app.py Co-authored-by: Jens Scheffler <95105677+jscheffl@users.noreply.github.com>
1 parent d508ff4 commit 21dae80

File tree

1 file changed

+12
-14
lines changed
  • airflow-core/src/airflow/api_fastapi

1 file changed

+12
-14
lines changed

airflow-core/src/airflow/api_fastapi/app.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import logging
2020
from contextlib import AsyncExitStack, asynccontextmanager
21+
from functools import cache
2122
from typing import TYPE_CHECKING, cast
2223
from urllib.parse import urlsplit
2324

@@ -64,8 +65,9 @@ def get_cookie_path() -> str:
6465

6566
log = 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
120123
def 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

128128
def 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

135134
def get_auth_manager_cls() -> type[BaseAuthManager]:
@@ -150,10 +149,9 @@ def get_auth_manager_cls() -> type[BaseAuthManager]:
150149

151150
def 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

159157
def init_auth_manager(app: FastAPI | None = None) -> BaseAuthManager:
@@ -171,12 +169,12 @@ def init_auth_manager(app: FastAPI | None = None) -> BaseAuthManager:
171169

172170
def 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

182180
def init_plugins(app: FastAPI) -> None:

0 commit comments

Comments
 (0)