Skip to content

Instantly share code, notes, and snippets.

@wshayes
Created January 19, 2020 17:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wshayes/70fb2d8b5b1c5efb8dbc1a549cbd5b55 to your computer and use it in GitHub Desktop.
Save wshayes/70fb2d8b5b1c5efb8dbc1a549cbd5b55 to your computer and use it in GitHub Desktop.
[Websockets with fastapi] #fastapi #websockets
# https://github.com/tiangolo/fastapi/issues/883#issuecomment-575913215
# You can probably use an async queue so your MQTT client will push messages to the queue and the WS server will get from the queue and send them to the WS client.
from asyncio import Queue
queue: Queue = None
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
global queue
queue = Queue()
while True:
msg = await queue.get()
await websocket.send_text({"message": msg})
async def on_mqtt_message(msg):
if queue:
await queue.put(msg)
# Note that the queue must be using the same event-loop as the WS, one way of doing it is to initialize the queue in the same function where you accept the WS.
# Also, assuming you want the WS client to receive all the MQTT messages, you should use a queue per WS.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment