Fastapi: [Question] Understanding Depends

Created on 24 Oct 2020  路  3Comments  路  Source: tiangolo/fastapi

I'm trying to understand the need for Depends. While I can see its use, I don't see how it differs from directly calling a function. For instance, in the fullstack project the get_db() is consistently used in a Depends. Why not simply call the get_db() within the route?

I apologize if its a dumb question, but I really can't find an appropriate answer.

question

Most helpful comment

The other reason, specifically in the case of get_db(), is that you can handle the open/close of the database in the Depends function. You can be assured that the database conn. will get closed in that case.

An alternative that is common in Python is using context managers to automatically call a close method. But if you use that approach, it's not always closed correctly, in my experience.

For instance, if you open some resource (e.g. a db conn or a file) with a context manager and from inside the context manager your return a StreamingResponse, I've run into issues. However, if you use a Depends method, with a try/yield/finally, as shown in the docs, everything gets cleaned up correctly, even using a StreamingResponse.

All 3 comments

The answer can be found at this stackoverflow page.

You can also read FastAPI doc on dependencies - Link

In essence, FastAPI uses Depends for dependency injection - i.e. to declare things that are required for it (a function for example) to work. It is a way to be pedantic of what your function needs.

The other reason, specifically in the case of get_db(), is that you can handle the open/close of the database in the Depends function. You can be assured that the database conn. will get closed in that case.

An alternative that is common in Python is using context managers to automatically call a close method. But if you use that approach, it's not always closed correctly, in my experience.

For instance, if you open some resource (e.g. a db conn or a file) with a context manager and from inside the context manager your return a StreamingResponse, I've run into issues. However, if you use a Depends method, with a try/yield/finally, as shown in the docs, everything gets cleaned up correctly, even using a StreamingResponse.

@falkben oh woah! I didn't know context manager's could fail. That's a great piece of information 馃憤馃徎

Was this page helpful?
0 / 5 - 0 ratings