KeyError: 'Session not found' #1213
Closed
KlaydKladowayIgr
started this conversation in
General
Replies: 4 comments 22 replies
-
On my windows PC its working |
Beta Was this translation helpful? Give feedback.
0 replies
-
Example from real code: #auth_handler.py
import logging
from fastapi.encoders import jsonable_encoder
from app.auth import sms
from app.auth.exceptions import SMSCodeSendError
from app.auth.models.limits import Limit
from app.auth.utils.sms_api import SMSBaseException
from app.main import sio
from app.ws.models import WSResponse
logger = logging.getLogger("gunicorn.error")
async def on_auth(sid, data: dict) -> dict:
logger.info(sid)
session: dict = await sio.get_session(sid)
if not session: await sio.save_session(sid, {})
if not data.get("phone"):
return jsonable_encoder(
WSResponse(
status=400,
type="error",
data={"details": "Incorrect data"}
)
)
if "token" in session:
return jsonable_encoder(
WSResponse(
status=403,
type="error",
data={"details": "You are already logged in"}
)
)
if not session.get("can_send", True):
return jsonable_encoder(
WSResponse(
status=403,
type="error",
data={"details": "You cannot resend the code using this function. Use auth_retry!"}
)
)
try:
code = await sms.send_code(data["phone"])
except SMSBaseException as e:
return jsonable_encoder(
WSResponse(
status=503,
type="error",
data={"details": f"SMS Service Error. {str(e)}"}
)
)
except SMSCodeSendError:
return jsonable_encoder(
WSResponse(
status=403,
type="error",
data={"details": "You cannot resend the code using this function. Use auth_retry!"}
)
)
await sio.save_session(sid, {"phone": data["phone"], "can_send": False})
limit = Limit(phone=data["phone"])
await limit.create()
return jsonable_encoder(
WSResponse(
status=200,
type="auth",
data=code
)
) #base_handler.py
from app.auth import tokens
from app.main import logger, sio
from app.ws.models import WSResponse
async def on_connect(sid, data: dict, auth: dict = None):
logger.info(f"Session: {sid} connected")
print(f"Session: {sid} connected")
logger.info(f"{sio.namespaces=}, {sio.namespace_handlers}")
#logger.info(f"EID: {sio.manager.eio_sid_from_sid(sid, '/')}")
#logger.info(f"EIO Sessions: {sio.eio.sockets}")
#logger.info(await sio.eio.get_session(sio.manager.eio_sid_from_sid(sid, '/')))
print(sio.eio.sockets)
if auth and not auth.get("token"):
await sio.emit(
"auth",
WSResponse(
status=400,
type="error",
data={"details": "Incorrect auth! "
"If you are logging in for the first time, log in using the auth method"}
).dict(),
to=sid
)
return
if auth:
auth_data = await tokens.authenticate(auth["token"])
if not auth_data:
await sio.emit(
"auth",
WSResponse(
status=403,
type="error",
data={"details": "Invalid token!"}
).dict(),
to=sid
)
return
sio.enter_room(sid, room=auth_data["user"].id)
await sio.save_session(sid, {"token": auth["token"], "phone": auth_data["user"].phone, "can_send": False})
logger.info(f"Session {sid} authenticated")
await sio.emit(
"auth",
WSResponse(
status=200,
type="info",
data=auth_data
).dict(),
to=sid
)
async def on_disconnect(sid):
logger.info(f"Session {sid} disconnected") #main.py
import asyncio
import importlib
import logging
import os
import sys
from inspect import getmembers, isfunction
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger
from fastapi import FastAPI
import socketio
import app.auth.sms as sms
import app.database as db
from app.admin.statistic.user import router as user_stat_router
from app.auth.models.auth import Tokens
from app.auth.models.limits import Limit
from app.auth.models.user import User, UserAuthCode
from app.chat.models import Message
from app.payments.models import Tariff, Order
from app.payments.router import router as payment_router
app = FastAPI()
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*")
sio_app = socketio.ASGIApp(sio, other_asgi_app=app)
app.mount("/ws", sio_app)
logger = logging.getLogger("gunicorn.error")
app.include_router(user_stat_router)
app.include_router(payment_router)
for root, dirs, files in os.walk("ws"):
for file in files:
if file.split('_')[-1][:-3] == "handler":
module = importlib.import_module(root.replace("/", ".") + '.' + file[:-3])
for handler in getmembers(module, isfunction):
if not handler[0].startswith("on_"): continue
sio.on(event=handler[0][3:], handler=handler[1])
@app.on_event("startup")
async def startup():
if sys.platform == "win32": asyncio.set_event_loop(asyncio.ProactorEventLoop())
await db.init_db([UserAuthCode, User, Message, Tokens, Limit, Tariff, Order])
scheduler = AsyncIOScheduler()
scheduler.add_job(sms.check_codes, trigger=IntervalTrigger(seconds=5))
scheduler.add_job(sms.check_limit, trigger=IntervalTrigger(seconds=5))
scheduler.start() |
Beta Was this translation helpful? Give feedback.
5 replies
-
The problem is solved, I just put the sio declaration in a separate file #server.py
import socketio
sio = socketio.AsyncServer() #main.py
from server import sio
for root, dirs, files in os.walk("ws"):
for file in files:
if file.split('_')[-1][:-3] == "handler":
module = importlib.import_module(root.replace("/", ".") + '.' + file[:-3])
for handler in getmembers(module, isfunction):
if not handler[0].startswith("on_"): continue
sio.on(event=handler[0][3:], handler=handler[1]) #auth_handler.py
from server import sio
async def on_auth(sid, data):
. . . |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello. I have error:
This is a very strange behavior, because other methods that do not use get_session and save_session work
I running on: Linux, Gunicorn, Nginx Proxy
Gunicorn:
Nginx:
Beta Was this translation helpful? Give feedback.
All reactions