pyropy / fastapi-socketio

Easily integrate socket.io with your FastAPI app 🚀
Apache License 2.0
330 stars 31 forks source link

sockets listenets on other file/directory #26

Open UtopiaBe opened 2 years ago

UtopiaBe commented 2 years ago

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.

hmajid2301 commented 2 years ago

Hi perhaps I'm misunderstanding but something like in the README example ? Here https://github.com/pyropy/fastapi-socketio#usage

shellking4 commented 2 years ago

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
falkoschindler commented 1 year ago

I don't understand. Wouldn't that introduce a circular import dependency?

In my project the server complains:

Error loading ASGI app. Could not import module "app.main".

TomW1605 commented 1 year ago

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