From 94ea1e92a8afdc47e6cb6c9a147b5915c8f03b2d Mon Sep 17 00:00:00 2001 From: Radoslav Georgiev Date: Sun, 3 Nov 2019 11:35:50 +0200 Subject: [PATCH] Add subsetion for structure --- README.md | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/README.md b/README.md index 71c053d..f3f77ec 100644 --- a/README.md +++ b/README.md @@ -964,6 +964,64 @@ def some_service_name(*args, **kwargs): This is a task, having the same name as a service, which holds the actual business logic. +### Structure + +#### Configuration + +We put Celery confguration in a Django app called `tasks`. The [Celery config](https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html) itself is located in `apps.py`, in `TasksConfig.ready` method. + +This Django app also holds any additional utilities, related to Celery. + +Here's an example `project/tasks/apps.py` file: + +```python +import os +from celery import Celery +from django.apps import apps, AppConfig +from django.conf import settings + + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') + + +app = Celery('project') + + +class TasksConfig(AppConfig): + name = 'project.tasks' + verbose_name = 'Celery Config' + + def ready(self): + app.config_from_object('django.conf:settings', namespace="CELERY") + app.autodiscover_tasks() + + +@app.task(bind=True) +def debug_task(self): + from celery.utils.log import base_logger + base_logger = base_logger + + base_logger.debug('debug message') + base_logger.info('info message') + base_logger.warning('warning message') + base_logger.error('error message') + base_logger.critical('critical message') + + print('Request: {0!r}'.format(self.request)) + + return 42 +``` + +#### Tasks + +Tasks are located in in `tasks.py` modules in different apps. + +We follow the same rules as with everything else (APIs, services, selectors): **if the tasks for a given app grow too big, split them by domain.** + +Meaning, you can end up with `tasks/domain_a.py` and `tasks/domain_b.py`. All you need to do is impor them in `tasks/__init__.py` for Celery to autodiscover them. + +The general rule of thumb is - split your tasks in a way that'll make sense to you. + ## Inspiration The way we do Django is inspired by the following things: