Selaa lähdekoodia

add session clean task in aiohttp & fastapi

wangweimin 3 vuotta sitten
vanhempi
säilyke
3fe47f47c8
3 muutettua tiedostoa jossa 13 lisäystä ja 1 poistoa
  1. 8 1
      pywebio/platform/adaptor/ws.py
  2. 2 0
      pywebio/platform/aiohttp.py
  3. 3 0
      pywebio/platform/fastapi.py

+ 8 - 1
pywebio/platform/adaptor/ws.py

@@ -30,7 +30,7 @@ class _state:
     # used to get the active conn in session's callbacks
     active_connections: Dict[str, 'WebSocketConnection'] = {}  # session_id -> WSHandler
 
-    expire_second = 10
+    expire_second = 0
 
 
 def set_expire_second(sec):
@@ -56,7 +56,14 @@ def clean_expired_sessions():
             session.close(nonblock=True)
 
 
+_session_clean_task_started = False
+
+
 async def session_clean_task():
+    global _session_clean_task_started
+    if _session_clean_task_started or not _state.expire_second:
+        return
+    _session_clean_task_started = True
     logger.debug("Start session cleaning task")
     while True:
         try:

+ 2 - 0
pywebio/platform/aiohttp.py

@@ -77,6 +77,8 @@ def _webio_handler(applications, cdn, websocket_settings, reconnect_timeout=0, c
     :param callable check_origin_func: check_origin_func(origin, host) -> bool
     :return: aiohttp Request Handler
     """
+    ws_adaptor.set_expire_second(reconnect_timeout)
+    asyncio.get_event_loop().create_task(ws_adaptor.session_clean_task())
 
     async def wshandle(request: web.Request):
         ioloop = asyncio.get_event_loop()

+ 3 - 0
pywebio/platform/fastapi.py

@@ -58,6 +58,9 @@ def _webio_routes(applications, cdn, check_origin_func, reconnect_timeout):
     :param callable check_origin_func: check_origin_func(origin, host) -> bool
     """
 
+    ws_adaptor.set_expire_second(reconnect_timeout)
+    asyncio.get_event_loop().create_task(ws_adaptor.session_clean_task())
+
     async def http_endpoint(request: Request):
         origin = request.headers.get('origin')
         if origin and not check_origin_func(origin=origin, host=request.headers.get('host')):