0

There is a class called MsvConfig in which I want to keep some app configurations. I want to load this class using Dependency Injection. One of settings I keep in config is CORS_origins.

def create_app() -> FastAPI:

    app = FastAPI(dependencies=[Depends(MsvConfig)])
    app.include_router(features.product_search.endpoints.endpoints.router)

    return app

app = create_app()

@app.on_event("startup")
async def startup_event(msv_config: MsvConfig = Depends(MsvConfig)):

    origins = msv_config.CORS_origins

    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

When I try to do it this way, I get an error:

AttributeError: 'Depends' object has no attribute 'CORS_origins'

Can you give me a hint how it should be solved? Every example of using Depends shows it on a FastAPI's http endpoints, but here I need to do something before any request arrives to my API.

Piotrek
  • 10,919
  • 18
  • 73
  • 136
  • If you want to execute some code before entering your route it's not a depends you need but a middleware (typically what you use for authentication) https://stackoverflow.com/questions/71525132/how-to-write-a-custom-fastapi-middleware-class https://fastapi.tiangolo.com/tutorial/middleware/ https://fastapi.tiangolo.com/advanced/middleware/ – Bastien B Aug 25 '23 at 15:18
  • but I do use middleware. My code exaple is adding CORSMiddleware at startup – Piotrek Aug 26 '23 at 11:27

1 Answers1

1

There is no need to use dependency injections in this case. Simply importing the class will suffice. Dependency injection in FastAPI is indented for reading data that is modified with every request.

Python does not double import modules that have already been imported.