Consuming a message in a FastAPI middleware

52 Views Asked by At

A little context: the FastAPI server I am developing will receive encrypted requests. In the encrypted body of this request, there will be both the headers and the body of the message, as well as the path to which the message should go.

The problem is that if I consume the message as I am doing in the code below, at an execution point where I can modify the scope (and the path), the server hangs because it tries to consume the message again (or that's what I understood).

class CustomMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] == "http":
            message = await receive()
            async def generate_messages():
                return message
            await self.app(scope, generate_messages, send)
        else:
            await self.app(scope, receive, send)

app.add_middleware(CustomMiddleware)

This is a pretty particular middleware use case, I know. But is there any way to reset the consumed message after consuming it? Or should I give up and try another strategy?

Thank you so much!

As I have shown, I have tried to deliver the consumed message in the generate_messages, but it does not seem to work.

I have also tried with the usual FastAPI structure of defining the middleware (https://fastapi.tiangolo.com/tutorial/middleware/), but the problem is the same.

0

There are 0 best solutions below