Skip to content

Commit 04a4a97

Browse files
authored
Merge pull request freqtrade#12974 from freqtrade/maint/migrate_add_event_handler
migrate fastapi add event handler
2 parents c112fa6 + 143d9a9 commit 04a4a97

2 files changed

Lines changed: 15 additions & 20 deletions

File tree

freqtrade/rpc/api_server/webserver.py

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
from contextlib import asynccontextmanager
23
from ipaddress import ip_address
34
from typing import Any
45

@@ -100,6 +101,19 @@ def render(self, content: Any) -> bytes:
100101
return orjson.dumps(content, option=orjson.OPT_SERIALIZE_NUMPY)
101102

102103

104+
@asynccontextmanager
105+
async def lifespan(app: FastAPI):
106+
# Startup logic
107+
if not ApiServer._message_stream:
108+
# Creates the MessageStream class on startup so it has access to the same event loop
109+
# as uvicorn
110+
ApiServer._message_stream = MessageStream()
111+
yield
112+
# Shutdown logic
113+
if ApiServer._message_stream:
114+
ApiServer._message_stream = None
115+
116+
103117
class ApiServer(RPCHandler):
104118
__instance = None
105119
__initialized = False
@@ -137,6 +151,7 @@ def __init__(self, config: Config, standalone: bool = False) -> None:
137151
redoc_url=None,
138152
default_response_class=FTJSONResponse,
139153
openapi_tags=_OPENAPI_TAGS,
154+
lifespan=lifespan,
140155
)
141156
self.configure_app(self.app, self._config)
142157
self.start_api()
@@ -261,24 +276,6 @@ def configure_app(self, app: FastAPI, config):
261276
)
262277

263278
app.add_exception_handler(RPCException, self.handle_rpc_exception)
264-
app.add_event_handler(event_type="startup", func=self._api_startup_event)
265-
app.add_event_handler(event_type="shutdown", func=self._api_shutdown_event)
266-
267-
async def _api_startup_event(self):
268-
"""
269-
Creates the MessageStream class on startup
270-
so it has access to the same event loop
271-
as uvicorn
272-
"""
273-
if not ApiServer._message_stream:
274-
ApiServer._message_stream = MessageStream()
275-
276-
async def _api_shutdown_event(self):
277-
"""
278-
Removes the MessageStream class on shutdown
279-
"""
280-
if ApiServer._message_stream:
281-
ApiServer._message_stream = None
282279

283280
def start_api(self):
284281
"""

requirements.txt

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,6 @@ sdnotify==0.3.2
3838

3939
# API Server
4040
fastapi==0.135.1
41-
# TODO: starlette should not be pinned, but had breaking changes in 1.0.0.
42-
starlette<1.0.0
4341
pydantic==2.12.5
4442
uvicorn==0.41.0
4543
pyjwt==2.12.1

0 commit comments

Comments
 (0)