Код: Выделить всё
def get_db():
try:
db = SessionLocal()
yield db
finally:
print("from finally block")
db.close()
< /code>
@app.get("/")
async def read_all(db: Session = Depends(get_db)):
res = db.query(models.Todos).all()
print("from endpoint")
return res
< /code>
result
INFO: 127.0.0.1:39088 - "GET /openapi.json HTTP/1.1" 200 OK
from endpoint
INFO: 127.0.0.1:39088 - "GET / HTTP/1.1" 200 OK
from finally block
< /code>
why does Depends(get_db) seem to act like somekind of contextmanager?.
the "from finally block"
, что делает что -то вроде
Код: Выделить всё
class SomeDependency:
def __enter__(self):
print("entering")
def __exit__(self, exc_type, exc_val, exc_tb):
print("exited")
def hello():
try:
yield SomeDependency()
finally:
print("yolo")
if __name__ == "__main__":
next(hello())
< /code>
the finally
Что почему, наконец, блок get_db не выполняется немедленно, когда передается, зависит ?
Подробнее здесь: https://stackoverflow.com/questions/753 ... ntextmanag