Created
January 19, 2020 17:06
-
-
Save wshayes/70fb2d8b5b1c5efb8dbc1a549cbd5b55 to your computer and use it in GitHub Desktop.
[Websockets with fastapi] #fastapi #websockets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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