Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/adriangb/asgi-background
Background tasks for ASGI web frameworks
https://github.com/adriangb/asgi-background
Last synced: 21 days ago
JSON representation
Background tasks for ASGI web frameworks
- Host: GitHub
- URL: https://github.com/adriangb/asgi-background
- Owner: adriangb
- License: mit
- Created: 2022-07-01T00:14:09.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2022-11-03T20:35:29.000Z (about 2 years ago)
- Last Synced: 2024-10-07T18:08:21.672Z (about 1 month ago)
- Language: Python
- Size: 59.6 KB
- Stars: 16
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
- awesome-asgi - asgi-background - Background tasks for any ASGI framework. (Resources / Experiments and examples)
README
# asgi-background
Background tasks for any ASGI framework.
## Example (Starlette)
```python
from asgi_background import BackgroundTaskMiddleware, BackgroundTasks
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Routeasync def task(num: int) -> None:
await anyio.sleep(1)
print(num)async def endpoint(request: Request) -> Response:
tasks = BackgroundTasks(request.scope)
await tasks.add_task(task, 1)
return Response()app = Starlette(
routes=[Route("/", endpoint)],
middleware=[Middleware(BackgroundTaskMiddleware)]
)
```## Execution
Unlike Starlette, we do not execute background tasks within the ASGI request/response cycle.
Instead we schedule them in a `TaskGroup` that is bound to the application's lifespan.
The only guarantee we make is that background tasks will not block (in the async sense, not the GIL sense) sending the response and that we will (try) to wait for them to finish when the application shuts down.
Just like with Starlette's background tasks, you should only use these for short lived tasks, they are not a durable queuing mechanisms like Redis, Celery, etc.
For context, the default application shutdown grace period in Kubernetes is 30 seconds, so 30 seconds is probably about as long as you should allow your tasks to run.