Feature Request: option to unconditionally run BackgroundTask in StreamingResponse #1153
Unanswered
AllSeeingEyeTolledEweSew
asked this question in
Ideas
Replies: 1 comment 3 replies
-
I just learned how async generators really work, and now I don't have a need for this feature. Given: async def generate() -> AsyncIterator[bytes]:
try:
yield ...
finally:
print("finally!") I learned that |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is your feature related to a problem? Please describe.
StreamingResponse
currently doesn't provide a natural way to release resources or do any tear-down. I can provide aBackgroundTask
toStreamingResponse
, but if an exception is thrown (either from the asgi send, or from my iterator itself), the task is never run.My use case: I'm building an HTTP bridge that streams data from bittorrent.
StreamingResponse
is a natural choice. My app has a singleton bittorrent client which downloads data from the swarm, and prioritizes among the active requests to my app. This downloading is slow, so it downloads data with a large buffer. If a request errors out, I want to notify the bittorrent client as quickly as possible, so it doesn't continue to download data unnecessarily.Describe the solution you would like.
One of
StreamingResponse
to always run itsBackgroundTask
, e.g. in afinally:
block in its__call__
. I expect this isn't acceptable since it would break some consumers. But I'm struggling to think of the case where a consumer really wants the task to not be run in the event of an error, so maybe this is the right choiceStreamingResponse(background=task, always_run_background=True)
, to ensure the task gets run as described above.Describe alternatives you considered
weakref
with finalizer (orIterable
with a__del__
) to do the cleanup. Depending on when gc runs, my cleanup code might not run immediately and I might continue to download unnecessary data. There are also a lot of arcane restrictions on what code may/should run in finalizers; I would much rather not need to think about theseStreamingResponse
myself: Easy enough, but awkward. I need to either re-implement__call__
, or do some things to ensure I don't call theBackgroundTask
twice:Beta Was this translation helpful? Give feedback.
All reactions