broadcaster icon indicating copy to clipboard operation
broadcaster copied to clipboard

MemoryBackend does not get event from asyncio.Queue, when app is running from PyCharm

Open ohiliazov opened this issue 4 years ago • 0 comments

Consider the following code from example, which works fine when running the file with command-line: uvicorn main:app

The same code has issues, when running with with PyCharm. The issue occurs at broadcaster/_backends/memory.py:30, where is cannot get an event from asyncio.Queue. I'm using python3.8.

from broadcaster import Broadcast
from starlette.applications import Starlette
from starlette.concurrency import run_until_first_complete
from starlette.routing import Route, WebSocketRoute
from starlette.templating import Jinja2Templates


broadcast = Broadcast("memory:///")
templates = Jinja2Templates("templates")


async def homepage(request):
    template = "index.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context)


async def chatroom_ws(websocket):
    await websocket.accept()
    await run_until_first_complete(
        (chatroom_ws_receiver, {"websocket": websocket}),
        (chatroom_ws_sender, {"websocket": websocket}),
    )


async def chatroom_ws_receiver(websocket):
    async for message in websocket.iter_text():
        await broadcast.publish(channel="chatroom", message=message)


async def chatroom_ws_sender(websocket):
    async with broadcast.subscribe(channel="chatroom") as subscriber:
        async for event in subscriber:
            await websocket.send_text(event.message)


routes = [
    Route("/", homepage),
    WebSocketRoute("/", chatroom_ws, name='chatroom_ws'),
]


app = Starlette(
    routes=routes, on_startup=[broadcast.connect], on_shutdown=[broadcast.disconnect],
)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app)

ohiliazov avatar Feb 04 '21 22:02 ohiliazov