Debian Codegraph @

docs/userguide/application.rst

raw
1 .. _guide-app:
2
3 =============
4 Application
5 =============
6
7 .. contents::
8 :local:
9 :depth: 1
10
11 The Celery library must be instantiated before use, this instance
12 is called an application (or *app* for short).
13
14 The application is thread-safe so that multiple Celery applications
15 with different configurations, components, and tasks can co-exist in the
16 same process space.
17
18 Let's create one now:
19
20 .. code-block:: pycon
21
22 >>> from celery import Celery
23 >>> app = Celery()
24 >>> app
25 <Celery __main__:0x100469fd0>
26
27 The last line shows the textual representation of the application:
28 including the name of the app class (``Celery``), the name of the
29 current main module (``__main__``), and the memory address of the object
30 (``0x100469fd0``).
31
32 Main Name
33 =========
34
35 Only one of these is important, and that's the main module name.
36 Let's look at why that is.
37
38 When you send a task message in Celery, that message won't contain
39 any source code, but only the name of the task you want to execute.
40 This works similarly to how host names work on the internet: every worker
41 maintains a mapping of task names to their actual functions, called the *task
42 registry*.
43
44 Whenever you define a task, that task will also be added to the local registry:
45
46 .. code-block:: pycon
47
48 >>> @app.task
49 ... def add(x, y):
50 ... return x + y
51
52 >>> add
53 <@task: __main__.add>
54
55 >>> add.name
56 __main__.add
57
58 >>> app.tasks['__main__.add']
59 <@task: __main__.add>
60
61 and there you see that ``__main__`` again; whenever Celery isn't able
62 to detect what module the function belongs to, it uses the main module
63 name to generate the beginning of the task name.
64
65 This is only a problem in a limited set of use cases:
66
67 #. If the module that the task is defined in is run as a program.
68 #. If the application is created in the Python shell (REPL).
69
70 For example here, where the tasks module is also used to start a worker
71 with :meth:`@worker_main`:
72
73 :file:`tasks.py`:
74
75 .. code-block:: python
76
77 from celery import Celery
78 app = Celery()
79
80 @app.task
81 def add(x, y): return x + y
82
83 if __name__ == '__main__':
84 args = ['worker', '--loglevel=INFO']
85 app.worker_main(argv=args)
86
87 When this module is executed the tasks will be named starting with "``__main__``",
88 but when the module is imported by another process, say to call a task,
89 the tasks will be named starting with "``tasks``" (the real name of the module):
90
91 .. code-block:: pycon
92
93 >>> from tasks import add
94 >>> add.name
95 tasks.add
96
97 You can specify another name for the main module:
98
99 .. code-block:: pycon
100
101 >>> app = Celery('tasks')
102 >>> app.main
103 'tasks'
104
105 >>> @app.task
106 ... def add(x, y):
107 ... return x + y
108
109 >>> add.name
110 tasks.add
111
112 .. seealso:: :ref:`task-names`
113
114 Configuration
115 =============
116
117 There are several options you can set that'll change how
118 Celery works. These options can be set directly on the app instance,
119 or you can use a dedicated configuration module.
120
121 The configuration is available as :attr:`@conf`:
122
123 .. code-block:: pycon
124
125 >>> app.conf.timezone
126 'Europe/London'
127
128 where you can also set configuration values directly:
129
130 .. code-block:: pycon
131
132 >>> app.conf.enable_utc = True
133
134 or update several keys at once by using the ``update`` method:
135
136 .. code-block:: python
137
138 >>> app.conf.update(
139 ... enable_utc=True,
140 ... timezone='Europe/London',
141 ...)
142
143 The configuration object consists of multiple dictionaries
144 that are consulted in order:
145
146 #. Changes made at run-time.
147 #. The configuration module (if any)
148 #. The default configuration (:mod:`celery.app.defaults`).
149
150 You can even add new default sources by using the :meth:`@add_defaults`
151 method.
152
153 .. seealso::
154
155 Go to the :ref:`Configuration reference <configuration>` for a complete
156 listing of all the available settings, and their default values.
157
158 ``config_from_object``
159 ----------------------
160
161 The :meth:`@config_from_object` method loads configuration
162 from a configuration object.
163
164 This can be a configuration module, or any object with configuration attributes.
165
166 Note that any configuration that was previously set will be reset when
167 :meth:`~@config_from_object` is called. If you want to set additional
168 configuration you should do so after.
169
170 Example 1: Using the name of a module
171 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
172
173 The :meth:`@config_from_object` method can take the fully qualified
174 name of a Python module, or even the name of a Python attribute,
175 for example: ``"celeryconfig"``, ``"myproj.config.celery"``, or
176 ``"myproj.config:CeleryConfig"``:
177
178 .. code-block:: python
179
180 from celery import Celery
181
182 app = Celery()
183 app.config_from_object('celeryconfig')
184
185 The ``celeryconfig`` module may then look like this:
186
187 :file:`celeryconfig.py`:
188
189 .. code-block:: python
190
191 enable_utc = True
192 timezone = 'Europe/London'
193
194 and the app will be able to use it as long as ``import celeryconfig`` is
195 possible.
196
197 Example 2: Passing an actual module object
198 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
199
200 You can also pass an already imported module object, but this
201 isn't always recommended.
202
203 .. tip::
204
205 Using the name of a module is recommended as this means the module does
206 not need to be serialized when the prefork pool is used. If you're
207 experiencing configuration problems or pickle errors then please
208 try using the name of a module instead.
209
210 .. code-block:: python
211
212 import celeryconfig
213
214 from celery import Celery
215
216 app = Celery()
217 app.config_from_object(celeryconfig)
218
219
220 Example 3: Using a configuration class/object
221 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
222
223 .. code-block:: python
224
225 from celery import Celery
226
227 app = Celery()
228
229 class Config:
230 enable_utc = True
231 timezone = 'Europe/London'
232
233 app.config_from_object(Config)
234 # or using the fully qualified name of the object:
235 # app.config_from_object('module:Config')
236
237 ``config_from_envvar``
238 ----------------------
239
240 The :meth:`@config_from_envvar` takes the configuration module name
241 from an environment variable
242
243 For example -- to load configuration from a module specified in the
244 environment variable named :envvar:`CELERY_CONFIG_MODULE`:
245
246 .. code-block:: python
247
248 import os
249 from celery import Celery
250
251 #: Set default configuration module name
252 os.environ.setdefault('CELERY_CONFIG_MODULE', 'celeryconfig')
253
254 app = Celery()
255 app.config_from_envvar('CELERY_CONFIG_MODULE')
256
257 You can then specify the configuration module to use via the environment:
258
259 .. code-block:: console
260
261 $ CELERY_CONFIG_MODULE="celeryconfig.prod" celery worker -l INFO
262
263 .. _app-censored-config:
264
265 Censored configuration
266 ----------------------
267
268 If you ever want to print out the configuration, as debugging information
269 or similar, you may also want to filter out sensitive information like
270 passwords and API keys.
271
272 Celery comes with several utilities useful for presenting the configuration,
273 one is :meth:`~celery.app.utils.Settings.humanize`:
274
275 .. code-block:: pycon
276
277 >>> app.conf.humanize(with_defaults=False, censored=True)
278
279 This method returns the configuration as a tabulated string. This will
280 only contain changes to the configuration by default, but you can include the
281 built-in default keys and values by enabling the ``with_defaults`` argument.
282
283 If you instead want to work with the configuration as a dictionary, you
284 can use the :meth:`~celery.app.utils.Settings.table` method:
285
286 .. code-block:: pycon
287
288 >>> app.conf.table(with_defaults=False, censored=True)
289
290 Please note that Celery won't be able to remove all sensitive information,
291 as it merely uses a regular expression to search for commonly named keys.
292 If you add custom settings containing sensitive information you should name
293 the keys using a name that Celery identifies as secret.
294
295 A configuration setting will be censored if the name contains any of
296 these sub-strings:
297
298 ``API``, ``TOKEN``, ``KEY``, ``SECRET``, ``PASS``, ``SIGNATURE``, ``DATABASE``
299
300 Laziness
301 ========
302
303 The application instance is lazy, meaning it won't be evaluated
304 until it's actually needed.
305
306 Creating a :class:`@Celery` instance will only do the following:
307
308 #. Create a logical clock instance, used for events.
309 #. Create the task registry.
310 #. Set itself as the current app (but not if the ``set_as_current``
311 argument was disabled)
312 #. Call the :meth:`@on_init` callback (does nothing by default).
313
314 The :meth:`@task` decorators don't create the tasks at the point when
315 the task is defined, instead it'll defer the creation
316 of the task to happen either when the task is used, or after the
317 application has been *finalized*,
318
319 This example shows how the task isn't created until
320 you use the task, or access an attribute (in this case :meth:`repr`):
321
322 .. code-block:: pycon
323
324 >>> @app.task
325 >>> def add(x, y):
326 ... return x + y
327
328 >>> type(add)
329 <class 'celery.local.PromiseProxy'>
330
331 >>> add.__evaluated__()
332 False
333
334 >>> add # <-- causes repr(add) to happen
335 <@task: __main__.add>
336
337 >>> add.__evaluated__()
338 True
339
340 *Finalization* of the app happens either explicitly by calling
341 :meth:`@finalize` -- or implicitly by accessing the :attr:`@tasks`
342 attribute.
343
344 Finalizing the object will:
345
346 #. Copy tasks that must be shared between apps
347
348 Tasks are shared by default, but if the
349 ``shared`` argument to the task decorator is disabled,
350 then the task will be private to the app it's bound to.
351
352 #. Evaluate all pending task decorators.
353
354 #. Make sure all tasks are bound to the current app.
355
356 Tasks are bound to an app so that they can read default
357 values from the configuration.
358
359 .. _default-app:
360
361 .. topic:: The "default app"
362
363 Celery didn't always have applications, it used to be that
364 there was only a module-based API. A compatibility API was
365 available at the old location until the release of Celery 5.0,
366 but has been removed.
367
368 Celery always creates a special app - the "default app",
369 and this is used if no custom application has been instantiated.
370
371 The :mod:`celery.task` module is no longer available. Use the
372 methods on the app instance, not the module based API:
373
374 .. code-block:: python
375
376 from celery.task import Task # << OLD Task base class.
377
378 from celery import Task # << NEW base class.
379
380
381 Breaking the chain
382 ==================
383
384 While it's possible to depend on the current app
385 being set, the best practice is to always pass the app instance
386 around to anything that needs it.
387
388 I call this the "app chain", since it creates a chain
389 of instances depending on the app being passed.
390
391 The following example is considered bad practice:
392
393 .. code-block:: python
394
395 from celery import current_app
396
397 class Scheduler:
398
399 def run(self):
400 app = current_app
401
402 Instead it should take the ``app`` as an argument:
403
404 .. code-block:: python
405
406 class Scheduler:
407
408 def __init__(self, app):
409 self.app = app
410
411 Internally Celery uses the :func:`celery.app.app_or_default` function
412 so that everything also works in the module-based compatibility API
413
414 .. code-block:: python
415
416 from celery.app import app_or_default
417
418 class Scheduler:
419 def __init__(self, app=None):
420 self.app = app_or_default(app)
421
422 In development you can set the :envvar:`CELERY_TRACE_APP`
423 environment variable to raise an exception if the app
424 chain breaks:
425
426 .. code-block:: console
427
428 $ CELERY_TRACE_APP=1 celery worker -l INFO
429
430
431 .. topic:: Evolving the API
432
433 Celery has changed a lot from 2009 since it was initially
434 created.
435
436 For example, in the beginning it was possible to use any callable as
437 a task:
438
439 .. code-block:: pycon
440
441 def hello(to):
442 return 'hello {0}'.format(to)
443
444 >>> from celery.execute import apply_async
445
446 >>> apply_async(hello, ('world!',))
447
448 or you could also create a ``Task`` class to set
449 certain options, or override other behavior
450
451 .. code-block:: python
452
453 from celery import Task
454 from celery.registry import tasks
455
456 class Hello(Task):
457 queue = 'hipri'
458
459 def run(self, to):
460 return 'hello {0}'.format(to)
461 tasks.register(Hello)
462
463 >>> Hello.delay('world!')
464
465 Later, it was decided that passing arbitrary call-able's
466 was an anti-pattern, since it makes it very hard to use
467 serializers other than pickle, and the feature was removed
468 in 2.0, replaced by task decorators:
469
470 .. code-block:: python
471
472 from celery import app
473
474 @app.task(queue='hipri')
475 def hello(to):
476 return 'hello {0}'.format(to)
477
478 Abstract Tasks
479 ==============
480
481 All tasks created using the :meth:`@task` decorator
482 will inherit from the application's base :attr:`~@Task` class.
483
484 You can specify a different base class using the ``base`` argument:
485
486 .. code-block:: python
487
488 @app.task(base=OtherTask):
489 def add(x, y):
490 return x + y
491
492 To create a custom task class you should inherit from the neutral base
493 class: :class:`celery.Task`.
494
495 .. code-block:: python
496
497 from celery import Task
498
499 class DebugTask(Task):
500
501 def __call__(self, *args, **kwargs):
502 print('TASK STARTING: {0.name}[{0.request.id}]'.format(self))
503 return self.run(*args, **kwargs)
504
505
506 .. tip::
507
508 If you override the task's ``__call__`` method, then it's very important
509 that you also call ``self.run`` to execute the body of the task. Do not
510 call ``super().__call__``. The ``__call__`` method of the neutral base
511 class :class:`celery.Task` is only present for reference. For optimization,
512 this has been unrolled into ``celery.app.trace.build_tracer.trace_task``
513 which calls ``run`` directly on the custom task class if no ``__call__``
514 method is defined.
515
516 The neutral base class is special because it's not bound to any specific app
517 yet. Once a task is bound to an app it'll read configuration to set default
518 values, and so on.
519
520 To realize a base class you need to create a task using the :meth:`@task`
521 decorator:
522
523 .. code-block:: python
524
525 @app.task(base=DebugTask)
526 def add(x, y):
527 return x + y
528
529 It's even possible to change the default base class for an application
530 by changing its :meth:`@Task` attribute:
531
532 .. code-block:: pycon
533
534 >>> from celery import Celery, Task
535
536 >>> app = Celery()
537
538 >>> class MyBaseTask(Task):
539 ... queue = 'hipri'
540
541 >>> app.Task = MyBaseTask
542 >>> app.Task
543 <unbound MyBaseTask>
544
545 >>> @app.task
546 ... def add(x, y):
547 ... return x + y
548
549 >>> add
550 <@task: __main__.add>
551
552 >>> add.__class__.mro()
553 [<class add of <Celery __main__:0x1012b4410>>,
554 <unbound MyBaseTask>,
555 <unbound Task>,
556 <type 'object'>]