简体   繁体   中英

RabbitMQ, Flask/fastapi and websockets

My system architecture looks very similar to the figure posted in the question here . The primary difference between my implementation and the posted question is that I'll be using fastapi/flask for the web-server (in python) and rabbitmq for messaging.

My high level pseudo code (using fastAPI) is as follows:

from fastapi import APIRouter
from starlette.responses import Response
router = APIRouter()

@router.post("/users/{message}")
async def provide_suggestions(message: str, response: Response):
    uuid = generate_uuid(message)
    message_dict = {"uuid": uuid, "data": message}.
    result = await post_message_to_rabbit_mq(message_dict)
    response.status_code = SOME_VALID_HTTP_RESPONSE_CODE # what would this be?

Question 1: What would the HTTP response code be? Basically, the web server needs to notify the client to come back after a certain period of time and check for result (and return suggestions then).

Once the web server posts message via rabbitmq, the workers would generate relevant suggestions based on the message (by looking up a database). This message along with the uuid would be posted back in another rabbitmq message queue. Now the web server becomes a consumer.

Question 2: Assuming the webserver is registered as a consumer for the message queue on the egress path, would the webserver get the data on a separate thread for the message queue?

Question 3: Instead of waiting for another HTTP request from the client to send the suggestions, can the client and the server communicate asynchronously via web-sockets ?

To answer your questions:

1: According to REST standards , status code 202 seems to do it here:

HTTP Status 202 indicates that request has been accepted for processing, but the processing has not been completed. This status code is useful when the actual operation is asynchronous in nature.

2: You would want a different process within the service to consume from the queue and update the local server database. This would generally not be a part of your fastapi webserver, but a seperate process. Your fastapi webserver could then query the local database every so often, or you could have a seperate endpoint on the webserver than can be called by this process when the database has been updated.

3: If you have client utilities that can deal with the websocket connection, then yes. See fastapi's documentation on it here . Otherwise it might be better to return status code 202 on the first request and have the client query the webserver every few seconds. Another option is to use a callback url, but that depends on the client's situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM