Merge pull request #12974 from freqtrade/maint/migrate_add_event_handler

migrate fastapi add event handler
This commit is contained in:
Matthias
2026-03-24 07:05:58 +01:00
committed by GitHub
2 changed files with 15 additions and 20 deletions
+15 -18
View File
@@ -1,4 +1,5 @@
import logging
from contextlib import asynccontextmanager
from ipaddress import ip_address
from typing import Any
@@ -100,6 +101,19 @@ class FTJSONResponse(JSONResponse):
return orjson.dumps(content, option=orjson.OPT_SERIALIZE_NUMPY)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup logic
if not ApiServer._message_stream:
# Creates the MessageStream class on startup so it has access to the same event loop
# as uvicorn
ApiServer._message_stream = MessageStream()
yield
# Shutdown logic
if ApiServer._message_stream:
ApiServer._message_stream = None
class ApiServer(RPCHandler):
__instance = None
__initialized = False
@@ -137,6 +151,7 @@ class ApiServer(RPCHandler):
redoc_url=None,
default_response_class=FTJSONResponse,
openapi_tags=_OPENAPI_TAGS,
lifespan=lifespan,
)
self.configure_app(self.app, self._config)
self.start_api()
@@ -261,24 +276,6 @@ class ApiServer(RPCHandler):
)
app.add_exception_handler(RPCException, self.handle_rpc_exception)
app.add_event_handler(event_type="startup", func=self._api_startup_event)
app.add_event_handler(event_type="shutdown", func=self._api_shutdown_event)
async def _api_startup_event(self):
"""
Creates the MessageStream class on startup
so it has access to the same event loop
as uvicorn
"""
if not ApiServer._message_stream:
ApiServer._message_stream = MessageStream()
async def _api_shutdown_event(self):
"""
Removes the MessageStream class on shutdown
"""
if ApiServer._message_stream:
ApiServer._message_stream = None
def start_api(self):
"""
-2
View File
@@ -38,8 +38,6 @@ sdnotify==0.3.2
# API Server
fastapi==0.135.1
# TODO: starlette should not be pinned, but had breaking changes in 1.0.0.
starlette<1.0.0
pydantic==2.12.5
uvicorn==0.41.0
pyjwt==2.12.1