NewsCrawler.org

FastAPI Depends with yield: when post-processing runs and how scope changes it

【FastAPI】Dependsで使うyieldの後処理
Image: zenn.dev

This Zenn article explains when the code after `yield` in a FastAPI dependency passed to `Depends()` runs. With the default `scope="request"`, that code runs after the response has been sent. With `scope="function"`, it runs before the response is sent, so a failure at that step can still be returned to the client as an error response.

The author shows that a commit[1] placed after `yield` can fail after the client has already received 201 Created. flush()[2] can succeed while the commit fails, for example when PostgreSQL checks a foreign key deferred to commit time. In an SQLite example, the route with `scope="function"` returns 409 Conflict, while the default route sends 201 Created first and then fails on commit; in both cases the task is not saved.

For streaming with SSE[3], the choice of scope depends on whether the database is needed while events are sent. With `scope="function"`, the session can be closed before streaming starts; with `scope="request"`, it stays open during the stream. The article also covers FastAPI version changes: in 0.106.0 post-processing moved before the response was sent, in 0.118.0 it moved back after, and in 0.121.0 `scope="function"` was added. A dependency with `yield` must yield exactly once.

Read the original zenn.dev

Sources

  • Zenn JA

    【FastAPI】Dependsで使うyieldの後処理

    3 likes0 bookmarks0 comments

Published: First seen: Читать по-русски

Open as a page