Python | FastApi/Uvicorn: How to pass a Queue to uvicorn.run(..)?

Viewed 158

What I tried

I tried first to pass it on as a parameter somehow within uvicorn.run(...) but have not been successfully on it (I didn't found a general placeholder I could use for it).

I also tried to use a global variable, but it seems to me that uvicorn run on a separate process, thereby the Queue address did not stayed constant.

Then I tried to pass on the memory storage reference of the queue (as string) via environment variable, but then I was not able to transfer that string address back to an object to use it within the server.

Does anyone know how to solve this and basically pass on a Queue to the (FastApi)uvicorn server?

from multiprocessing import Queue
from multiprocessing import Process
import uvicorn as uvicorn
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

class WSServer:
    def __init__(self): pass

    def run(self, queue):
        # how can I pass the --> queue <-- inside the uvicorn(FastApi) server?
        uvicorn.run("server:app", host="0.0.0.0", port=8081, reload=True, access_log=False) 

main_queue: Queue = Queue() 
proc = Process(target=WSServer().run,name="Process: Simple Server",args=(main_queue,))
proc.start()

------------

app = FastAPI()

@app.websocket("/")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            msg = await websocket.receive_text()
            ...
            # here it would be lovely if I could use the "queue"...
0 Answers
Related