2018-10-02 10:40:08 +00:00
|
|
|
|
2018-10-02 10:47:49 +00:00
|
|
|
Starlette includes a `BackgroundTask` class for in-process background tasks.
|
|
|
|
|
|
|
|
A background task should be attached to a response, and will run only once
|
|
|
|
the response has been sent.
|
2018-10-02 10:40:08 +00:00
|
|
|
|
|
|
|
### Background Task
|
|
|
|
|
2018-10-05 15:38:02 +00:00
|
|
|
Signature: `BackgroundTask(func, *args, **kwargs)`
|
2018-10-02 10:40:08 +00:00
|
|
|
|
|
|
|
```python
|
|
|
|
from starlette.applications import Starlette
|
|
|
|
from starlette.responses import JSONResponse
|
|
|
|
from starlette.background import BackgroundTask
|
|
|
|
|
|
|
|
app = Starlette()
|
|
|
|
|
|
|
|
@app.route('/user/signup', methods=['POST'])
|
2018-10-02 10:47:49 +00:00
|
|
|
async def signup(request):
|
|
|
|
data = await request.json()
|
|
|
|
username = data['username']
|
|
|
|
email = data['email']
|
|
|
|
task = BackgroundTask(send_welcome_email, to_address=email)
|
|
|
|
message = {'status': 'Signup successful'}
|
|
|
|
return JSONResponse(message, background=task)
|
|
|
|
|
|
|
|
async def send_welcome_email(to_address):
|
|
|
|
...
|
|
|
|
```
|