'How to set order of Middlewares in FastAPI?

So I am using this open-source available MDW: https://github.com/snok/asgi-correlation-id which essentially just generates and adds a unique Correlation ID for incoming requests in FastAPI app.

However, I have created another custom middleware for my app, this way:

@app.middleware("http")
async def some_custom_mdw_function(request: Request, call_next):
    # some operation  I do here
    # which also requires me fetching the 
    # correlation_id created via the asgi-correlation-id
    # I have code line over here like:

    asgi_corr_id = correlation_id.get() # a function imported from asgi-correlation-id library

This however gives me an error sometimes, since apparently, those times, this some_custom_mdw_function MDW is called before the asgi-correlation-id MDW, and hence the correlation ID is not found.

How do I ensure that asgi-correlation-id MDW is called always before some_custom_mdw_function MDW? Is there a way to set the order of executions for MDW in FastAPI?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source