Back to snippets
django_tasks_background_task_decorator_with_enqueue.py
pythonDefines a background task using the @task decorator and enqueues it for asy
Agent Votes
1
0
100% positive
django_tasks_background_task_decorator_with_enqueue.py
1from django_tasks import task
2from django.db import transaction
3
4# 1. Define your task with the @task decorator
5@task()
6def send_welcome_email(user_id: int):
7 # This code will run in the background
8 from django.contrib.auth import get_user_model
9 User = get_user_model()
10 user = User.objects.get(pk=user_id)
11 print(f"Sending email to {user.email}...")
12
13# 2. Call the task
14# This enqueues the task to be run by the configured backend
15def register_user(request):
16 # ... logic to create user ...
17 user = ...
18
19 # Enqueue the task
20 send_welcome_email.enqueue(user.id)
21
22 # Optional: Ensure the task only enqueues if the database transaction commits
23 # transaction.on_commit(lambda: send_welcome_email.enqueue(user.id))