File: guide.rst

package info (click to toggle)
celery 5.5.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,008 kB
  • sloc: python: 64,346; sh: 795; makefile: 378
file content (334 lines) | stat: -rw-r--r-- 8,586 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
.. _internals-guide:

================================
 Contributors Guide to the Code
================================

.. contents::
    :local:

Philosophy
==========

The API>RCP Precedence Rule
---------------------------

- The API is more important than Readability
- Readability is more important than Convention
- Convention is more important than Performance
    - …unless the code is a proven hot-spot.

More important than anything else is the end-user API.
Conventions must step aside, and any suffering is always alleviated
if the end result is a better API.

Conventions and Idioms Used
===========================

Classes
-------

Naming
~~~~~~

- Follows :pep:`8`.

- Class names must be `CamelCase`.
- but not if they're verbs, verbs shall be `lower_case`:

    .. code-block:: python

        # - test case for a class
        class TestMyClass(Case):                # BAD
            pass

        class test_MyClass(Case):               # GOOD
            pass

        # - test case for a function
        class TestMyFunction(Case):             # BAD
            pass

        class test_my_function(Case):           # GOOD
            pass

        # - "action" class (verb)
        class UpdateTwitterStatus:    # BAD
            pass

        class update_twitter_status:    # GOOD
            pass

    .. note::

        Sometimes it makes sense to have a class mask as a function,
        and there's precedence for this in the Python standard library (e.g.,
        :class:`~contextlib.contextmanager`). Celery examples include
        :class:`~celery.signature`, :class:`~celery.chord`,
        ``inspect``, :class:`~kombu.utils.functional.promise` and more..

- Factory functions and methods must be `CamelCase` (excluding verbs):

    .. code-block:: python

        class Celery:

            def consumer_factory(self):     # BAD
                ...

            def Consumer(self):             # GOOD
                ...

Default values
~~~~~~~~~~~~~~

Class attributes serve as default values for the instance,
as this means that they can be set by either instantiation or inheritance.

**Example:**

.. code-block:: python

    class Producer:
        active = True
        serializer = 'json'

        def __init__(self, serializer=None, active=None):
            self.serializer = serializer or self.serializer

            # must check for None when value can be false-y
            self.active = active if active is not None else self.active

A subclass can change the default value:

.. code-block:: python

    TaskProducer(Producer):
        serializer = 'pickle'

and the value can be set at instantiation:

.. code-block:: pycon

    >>> producer = TaskProducer(serializer='msgpack')

Exceptions
~~~~~~~~~~

Custom exceptions raised by an objects methods and properties
should be available as an attribute and documented in the
method/property that throw.

This way a user doesn't have to find out where to import the
exception from, but rather use ``help(obj)`` and access
the exception class from the instance directly.

**Example**:

.. code-block:: python

    class Empty(Exception):
        pass

    class Queue:
        Empty = Empty

        def get(self):
            """Get the next item from the queue.

            :raises Queue.Empty: if there are no more items left.

            """
            try:
                return self.queue.popleft()
            except IndexError:
                raise self.Empty()

Composites
~~~~~~~~~~

Similarly to exceptions, composite classes should be override-able by
inheritance and/or instantiation. Common sense can be used when
selecting what classes to include, but often it's better to add one
too many: predicting what users need to override is hard (this has
saved us from many a monkey patch).

**Example**:

.. code-block:: python

    class Worker:
        Consumer = Consumer

        def __init__(self, connection, consumer_cls=None):
            self.Consumer = consumer_cls or self.Consumer

        def do_work(self):
            with self.Consumer(self.connection) as consumer:
                self.connection.drain_events()

Applications vs. "single mode"
==============================

In the beginning Celery was developed for Django, simply because
this enabled us get the project started quickly, while also having
a large potential user base.

In Django there's a global settings object, so multiple Django projects
can't co-exist in the same process space, this later posed a problem
for using Celery with frameworks that don't have this limitation.

Therefore the app concept was introduced. When using apps you use 'celery'
objects instead of importing things from Celery sub-modules, this
(unfortunately) also means that Celery essentially has two API's.

Here's an example using Celery in single-mode:

.. code-block:: python

    from celery import task
    from celery.task.control import inspect

    from .models import CeleryStats

    @task
    def write_stats_to_db():
        stats = inspect().stats(timeout=1)
        for node_name, reply in stats:
            CeleryStats.objects.update_stat(node_name, stats)


and here's the same using Celery app objects:

.. code-block:: python

    from .celery import celery
    from .models import CeleryStats

    @app.task
    def write_stats_to_db():
        stats = celery.control.inspect().stats(timeout=1)
        for node_name, reply in stats:
            CeleryStats.objects.update_stat(node_name, stats)


In the example above the actual application instance is imported
from a module in the project, this module could look something like this:

.. code-block:: python

    from celery import Celery

    app = Celery(broker='amqp://')


Module Overview
===============

- celery.app

    This is the core of Celery: the entry-point for all functionality.

- celery.loaders

    Every app must have a loader. The loader decides how configuration
    is read; what happens when the worker starts; when a task starts and ends;
    and so on.

    The loaders included are:

        - app

            Custom Celery app instances uses this loader by default.

        - default

            "single-mode" uses this loader by default.

    Extension loaders also exist, for example :pypi:`celery-pylons`.

- celery.worker

    This is the worker implementation.

- celery.backends

    Task result backends live here.

- celery.apps

    Major user applications: worker and beat.
    The command-line wrappers for these are in celery.bin (see below)

- celery.bin

    Command-line applications.
    :file:`setup.py` creates setuptools entry-points for these.

- celery.concurrency

    Execution pool implementations (prefork, eventlet, gevent, solo, thread).

- celery.db

    Database models for the SQLAlchemy database result backend.
    (should be moved into :mod:`celery.backends.database`)

- celery.events

    Sending and consuming monitoring events, also includes curses monitor,
    event dumper and utilities to work with in-memory cluster state.

- celery.execute.trace

    How tasks are executed and traced by the worker, and in eager mode.

- celery.security

    Security related functionality, currently a serializer using
    cryptographic digests.

- celery.task

    single-mode interface to creating tasks, and controlling workers.

- t.unit (int distribution)

    The unit test suite.

- celery.utils

    Utility functions used by the Celery code base.
    Much of it is there to be compatible across Python versions.

- celery.contrib

    Additional public code that doesn't fit into any other name-space.

Worker overview
===============

* `celery.bin.worker:Worker`

   This is the command-line interface to the worker.

   Responsibilities:
       * Daemonization when :option:`--detach <celery worker --detach>` set,
       * dropping privileges when using :option:`--uid <celery worker --uid>`/
         :option:`--gid <celery worker --gid>` arguments
       * Installs "concurrency patches" (eventlet/gevent monkey patches).

  ``app.worker_main(argv)`` calls
  ``instantiate('celery.bin.worker:Worker')(app).execute_from_commandline(argv)``

* `app.Worker` -> `celery.apps.worker:Worker`

   Responsibilities:
   * sets up logging and redirects standard outs
   * installs signal handlers (`TERM`/`HUP`/`STOP`/`USR1` (cry)/`USR2` (rdb))
   * prints banner and warnings (e.g., pickle warning)
   * handles the :option:`celery worker --purge` argument

* `app.WorkController` -> `celery.worker.WorkController`

   This is the real worker, built up around bootsteps.