OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to add a middleware before the application starts up in FastAPI?

  • Thread starter Thread starter Dante
  • Start date Start date
D

Dante

Guest
Using Lifespan Events and Middleware, I would like to add a middleware inside an asynccontextmanager. It should look something like this:

Code:
@asynccontextmanager
async def lifespan(app: FastAPI):
    if some_condition:
        @app.middleware("http")
        async def my_middleware(request: Request, call_next):
            response = await call_next(request)
            return response
    yield
    pass


app = FastAPI(lifespan=lifespan)

However, the example above raises the following error:

Code:
RuntimeError: Cannot add middleware after an application has started

But, in the beginning of Lifespan Events documentation, it is mentioned that:

You can define logic (code) that should be executed before the application starts up. This means that this code will be executed once, before the application starts receiving requests.

How should I approach this?
<p>Using <a href="https://fastapi.tiangolo.com/advanced/events/" rel="nofollow noreferrer">Lifespan Events</a> and <a href="https://fastapi.tiangolo.com/tutorial/middleware/" rel="nofollow noreferrer">Middleware</a>, I would like to add a middleware inside an <code>asynccontextmanager</code>. It should look something like this:</p>
<pre><code>@asynccontextmanager
async def lifespan(app: FastAPI):
if some_condition:
@app.middleware("http")
async def my_middleware(request: Request, call_next):
response = await call_next(request)
return response
yield
pass


app = FastAPI(lifespan=lifespan)
</code></pre>
<p>However, the example above raises the following error:</p>
<pre><code>RuntimeError: Cannot add middleware after an application has started
</code></pre>
<p>But, in the beginning of <a href="https://fastapi.tiangolo.com/advanced/events/" rel="nofollow noreferrer">Lifespan Events</a> documentation, it is mentioned that:</p>
<blockquote>
<p>You can define logic (code) that should be executed <strong>before the
application starts up</strong>. This means that this code will be executed
once, <strong>before the application starts</strong> receiving requests.</p>
</blockquote>
<p>How should I approach this?</p>
 

Latest posts

Top