Welcome back to CodeYourCraft! Today, we're diving into an exciting topic - Celery with Django. This powerful combination allows us to process tasks asynchronously, making our applications more efficient and responsive. Let's get started!
Celery is a distributed task queue based on the message passing paradigm. It is used to offload time-consuming tasks from a web application, allowing for better performance and scalability. Celery can be integrated seamlessly with Django to create robust, asynchronous applications.
pip install celerypip install redispython manage.py startapp celery_appcelery_app/ celery.py:from celery import Celery
app = Celery('celery_app')
app.conf.beat_schedule = {
'run-every-minutes': {
'task': 'celery_app.tasks.example_task',
'schedule': 60.0,
},
}
if __name__ == "__main__":
app.start()celery_app/tasks.py:from celery import shared_task
@shared_task
def example_task():
print("Example task is running...")celery_app/__init__.py file:INSTALLED_APPS = [
...
'celery_app',
...
]from django.urls import path, include
urlpatterns = [
...
path('admin/', admin.site.urls),
path('api/', include('celery_app.urls')),
...
]settings.py file:BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'celery -A celery_app worker --loglevel=infoNow that Celery is set up, let's run the example task:
celery_app/views.py:from django.http import HttpResponse
from celery_app.tasks import example_task
def run_example_task(request):
example_task.apply_async(countdown=10)
return HttpResponse("Example task scheduled to run in 10 seconds.")from django.urls import path
from . import views
urlpatterns = [
path('run_task/', views.run_example_task, name='run_task'),
...
]Now, if you navigate to http://localhost:8000/run_task/, you'll see the message "Example task scheduled to run in 10 seconds." After 10 seconds, the example task will run in the background.
In Celery, tasks are functions that can be executed asynchronously. Results of these tasks can be retrieved, allowing you to handle the results in your application.
result = example_task.apply_async(args=[1, 2, 3])result.get(timeout=60)That's it for today! You've learned how to set up and use Celery with Django. In the next lesson, we'll delve deeper into Celery tasks, task scheduling, and task results.
What is Celery used for?
Happy learning, and see you in the next lesson! π