fastapi-socketio
fastapi-socketio copied to clipboard
sockets listenets on other file/directory
Hey, how can i write my sockets on other folder/file and to tell my main.py to execute them?
my main file:
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
def get_application():
app = FastAPI(title="Evil Islands", version="1.0.0", redoc_url=None)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:8080"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
return app
app = get_application()
I want to place @app.sio listeners to a directory - lets say ../sockets
thank you.
Hi perhaps I'm misunderstanding but something like in the README example ? Here https://github.com/pyropy/fastapi-socketio#usage
Hey, how can i write my sockets on other folder/file and to tell my main.py to execute them?
my main file:
from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware def get_application(): app = FastAPI(title="Evil Islands", version="1.0.0", redoc_url=None) app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:8080"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) return app app = get_application()
I want to place @app.sio listeners to a directory - lets say ../sockets
thank you.
You can do so but make sure to include in the main app entry app.py or main.py (which means where the fastapi object has been instantiated) the import of the module where those socket listeners are
to show case what I'm saying, here is a basic example
# main.py
import socket_handlers.socket_handler
app = FastAPI(title="Evil Islands", version="1.0.0", redoc_url=None)
socket_manager = SocketManager(app=app)
# socket_handlers/socket_handler.py
from main import socket_manager as sm
@sm.on('send test result')
async def test_socketio(sid, *args, **kwargs) -> any:
print("received event from client")
await sm.emit("test result", { "test result": "your test result is here" })
return
I don't understand. Wouldn't that introduce a circular import dependency?
-
main.py
wantssocket_handler.py
. - But
socket_handler.py
needssocket_manager
frommain.py
, which is only created after importingsocket_handler.py
.
In my project the server complains:
Error loading ASGI app. Could not import module "app.main".
hi, im trying to do the same thing and getting the same error. any guidence would be welcome
EDIT: found a sloution here: https://haseebmajid.dev/posts/2021-12-31-separate-function-handler-modules-when-using-python-socketio/
TL; DR: have a seprate __init__.py
file that imports both the socket handler and the FastAPI app then runs the uvicorn function to start the server