application.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. .. _guide-app:
  2. =============
  3. Application
  4. =============
  5. .. contents::
  6. :local:
  7. :depth: 1
  8. The Celery library must be instantiated before use, this instance
  9. is called an application (or *app* for short).
  10. The application is thread-safe so that multiple Celery applications
  11. with different configuration, components and tasks can co-exist in the
  12. same process space.
  13. Let's create one now:
  14. .. code-block:: python
  15. >>> from celery import Celery
  16. >>> app = Celery()
  17. >>> app
  18. <Celery __main__:0x100469fd0>
  19. The last line shows the textual representation of the application,
  20. which includes the name of the celery class (``Celery``), the name of the
  21. current main module (``__main__``), and the memory address of the object
  22. (``0x100469fd0``).
  23. Main Name
  24. =========
  25. Only one of these is important, and that is the main module name,
  26. let's look at why that is.
  27. When you send a task message in Celery, that message will not contain
  28. any source code, but only the name of the task you want to execute.
  29. This works similarly to how host names works on the internet: every worker
  30. maintains a mapping of task names to their actual functions, called the *task
  31. registry*.
  32. Whenever you define a task, that task will also be added to the local registry:
  33. .. code-block:: python
  34. >>> @app.task
  35. ... def add(x, y):
  36. ... return x + y
  37. >>> add
  38. <@task: __main__.add>
  39. >>> add.name
  40. __main__.add
  41. >>> app.tasks['__main__.add']
  42. <@task: __main__.add>
  43. and there you see that ``__main__`` again; whenever Celery is not able
  44. to detect what module the function belongs to, it uses the main module
  45. name to generate the beginning of the task name.
  46. This is only a problem in a limited set of use cases:
  47. #. If the module that the task is defined in is run as a program.
  48. #. If the application is created in the Python shell (REPL).
  49. For example here, where the tasks module is also used to start a worker:
  50. :file:`tasks.py`:
  51. .. code-block:: python
  52. from celery import Celery
  53. app = Celery()
  54. @app.task
  55. def add(x, y): return x + y
  56. if __name__ == '__main__':
  57. app.worker_main()
  58. When this module is executed the tasks will be named starting with "``__main__``",
  59. but when the module is imported by another process, say to call a task,
  60. the tasks will be named starting with "``tasks``" (the real name of the module)::
  61. >>> from tasks import add
  62. >>> add.name
  63. tasks.add
  64. You can specify another name for the main module:
  65. .. code-block:: python
  66. >>> app = Celery('tasks')
  67. >>> app.main
  68. 'tasks'
  69. >>> @app.task
  70. ... def add(x, y):
  71. ... return x + y
  72. >>> add.name
  73. tasks.add
  74. .. seealso:: :ref:`task-names`
  75. Configuration
  76. =============
  77. There are several options you can set that will change how
  78. Celery works. These options can be set directly on the app instance,
  79. or you can use a dedicated configuration module.
  80. The configuration is available as :attr:`@Celery.conf`::
  81. >>> app.conf.CELERY_TIMEZONE
  82. 'Europe/London'
  83. where you can also set configuration values directly::
  84. >>> app.conf.CELERY_ENABLE_UTC = True
  85. and update several keys at once by using the ``update`` method::
  86. >>> app.conf.update(
  87. ... CELERY_ENABLE_UTC=True,
  88. ... CELERY_TIMEZONE='Europe/London',
  89. ...)
  90. The configuration object consists of multiple dictionaries
  91. that are consulted in order:
  92. #. Changes made at runtime.
  93. #. The configuration module (if any)
  94. #. The default configuration (:mod:`celery.app.defaults`).
  95. You can even add new default sources by using the :meth:`@Celery.add_defaults`
  96. method.
  97. .. seealso::
  98. Go to the :ref:`Configuration reference <configuration>` for a complete
  99. listing of all the available settings, and their default values.
  100. ``config_from_object``
  101. ----------------------
  102. The :meth:`@Celery.config_from_object` method loads configuration
  103. from a configuration object.
  104. This can be a configuration module, or any object with configuration attributes.
  105. Note that any configuration that was previous set will be reset when
  106. :meth:`~@Celery.config_from_object` is called. If you want to set additional
  107. configuration you should do so after.
  108. Example 1: Using the name of a module
  109. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  110. .. code-block:: python
  111. from celery import Celery
  112. app = Celery()
  113. app.config_from_object('celeryconfig')
  114. The ``celeryconfig`` module may then look like this:
  115. :file:`celeryconfig.py`:
  116. .. code-block:: python
  117. CELERY_ENABLE_UTC = True
  118. CELERY_TIMEZONE = 'Europe/London'
  119. Example 2: Using a configuration module
  120. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  121. .. tip::
  122. Using the name of a module is recomended
  123. as this means that the module doesn't need to be serialized
  124. when the prefork pool is used. If you're
  125. experiencing configuration pickle errors then please try using
  126. the name of a module instead.
  127. .. code-block:: python
  128. from celery import Celery
  129. app = Celery()
  130. import celeryconfig
  131. app.config_from_object(celeryconfig)
  132. Example 3: Using a configuration class/object
  133. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  134. .. code-block:: python
  135. from celery import Celery
  136. app = Celery()
  137. class Config:
  138. CELERY_ENABLE_UTC = True
  139. CELERY_TIMEZONE = 'Europe/London'
  140. app.config_from_object(Config)
  141. # or using the fully qualified name of the object:
  142. # app.config_from_object('module:Config')
  143. ``config_from_envvar``
  144. ----------------------
  145. The :meth:`@Celery.config_from_envvar` takes the configuration module name
  146. from an environment variable
  147. For example -- to load configuration from a module specified in the
  148. environment variable named :envvar:`CELERY_CONFIG_MODULE`:
  149. .. code-block:: python
  150. import os
  151. from celery import Celery
  152. #: Set default configuration module name
  153. os.environ.setdefault('CELERY_CONFIG_MODULE', 'celeryconfig')
  154. app = Celery()
  155. app.config_from_envvar('CELERY_CONFIG_MODULE')
  156. You can then specify the configuration module to use via the environment:
  157. .. code-block:: bash
  158. $ CELERY_CONFIG_MODULE="celeryconfig.prod" celery worker -l info
  159. .. _app-censored-config:
  160. Censored configuration
  161. ----------------------
  162. If you ever want to print out the configuration, as debugging information
  163. or similar, you may also want to filter out sensitive information like
  164. passwords and API keys.
  165. Celery comes with several utilities used for presenting the configuration,
  166. one is :meth:`~celery.app.utils.Settings.humanize`:
  167. .. code-block:: python
  168. >>> app.conf.humanize(with_defaults=False, censored=True)
  169. This method returns the configuration as a tabulated string. This will
  170. only contain changes to the configuration by default, but you can include the
  171. default keys and values by changing the ``with_defaults`` argument.
  172. If you instead want to work with the configuration as a dictionary, then you
  173. can use the :meth:`~celery.app.utils.Settings.table` method:
  174. .. code-block:: python
  175. >>> app.conf.table(with_defaults=False, censored=True)
  176. Please note that Celery will not be able to remove all sensitive information,
  177. as it merely uses a regular expression to search for commonly named keys.
  178. If you add custom settings containing sensitive information you should name
  179. the keys using a name that Celery identifies as secret.
  180. A configuration setting will be censored if the name contains any of
  181. these substrings:
  182. ``API``, ``TOKEN``, ``KEY``, ``SECRET``, ``PASS``, ``SIGNATURE``, ``DATABASE``
  183. Laziness
  184. ========
  185. The application instance is lazy, meaning that it will not be evaluated
  186. until something is actually needed.
  187. Creating a :class:`@Celery` instance will only do the following:
  188. #. Create a logical clock instance, used for events.
  189. #. Create the task registry.
  190. #. Set itself as the current app (but not if the ``set_as_current``
  191. argument was disabled)
  192. #. Call the :meth:`@Celery.on_init` callback (does nothing by default).
  193. The :meth:`~@Celery.task` decorator does not actually create the
  194. tasks at the point when it's called, instead it will defer the creation
  195. of the task to happen either when the task is used, or after the
  196. application has been *finalized*,
  197. This example shows how the task is not created until
  198. you use the task, or access an attribute (in this case :meth:`repr`):
  199. .. code-block:: python
  200. >>> @app.task
  201. >>> def add(x, y):
  202. ... return x + y
  203. >>> type(add)
  204. <class 'celery.local.PromiseProxy'>
  205. >>> add.__evaluated__()
  206. False
  207. >>> add # <-- causes repr(add) to happen
  208. <@task: __main__.add>
  209. >>> add.__evaluated__()
  210. True
  211. *Finalization* of the app happens either explicitly by calling
  212. :meth:`@Celery.finalize` -- or implicitly by accessing the :attr:`~@Celery.tasks`
  213. attribute.
  214. Finalizing the object will:
  215. #. Copy tasks that must be shared between apps
  216. Tasks are shared by default, but if the
  217. ``shared`` argument to the task decorator is disabled,
  218. then the task will be private to the app it's bound to.
  219. #. Evaluate all pending task decorators.
  220. #. Make sure all tasks are bound to the current app.
  221. Tasks are bound to apps so that it can read default
  222. values from the configuration.
  223. .. _default-app:
  224. .. topic:: The "default app".
  225. Celery did not always work this way, it used to be that
  226. there was only a module-based API, and for backwards compatibility
  227. the old API is still there.
  228. Celery always creates a special app that is the "default app",
  229. and this is used if no custom application has been instantiated.
  230. The :mod:`celery.task` module is there to accommodate the old API,
  231. and should not be used if you use a custom app. You should
  232. always use the methods on the app instance, not the module based API.
  233. For example, the old Task base class enables many compatibility
  234. features where some may be incompatible with newer features, such
  235. as task methods:
  236. .. code-block:: python
  237. from celery.task import Task # << OLD Task base class.
  238. from celery import Task # << NEW base class.
  239. The new base class is recommended even if you use the old
  240. module-based API.
  241. Breaking the chain
  242. ==================
  243. While it's possible to depend on the current app
  244. being set, the best practice is to always pass the app instance
  245. around to anything that needs it.
  246. I call this the "app chain", since it creates a chain
  247. of instances depending on the app being passed.
  248. The following example is considered bad practice:
  249. .. code-block:: python
  250. from celery import current_app
  251. class Scheduler(object):
  252. def run(self):
  253. app = current_app
  254. Instead it should take the ``app`` as an argument:
  255. .. code-block:: python
  256. class Scheduler(object):
  257. def __init__(self, app):
  258. self.app = app
  259. Internally Celery uses the :func:`celery.app.app_or_default` function
  260. so that everything also works in the module-based compatibility API
  261. .. code-block:: python
  262. from celery.app import app_or_default
  263. class Scheduler(object):
  264. def __init__(self, app=None):
  265. self.app = app_or_default(app)
  266. In development you can set the :envvar:`CELERY_TRACE_APP`
  267. environment variable to raise an exception if the app
  268. chain breaks:
  269. .. code-block:: bash
  270. $ CELERY_TRACE_APP=1 celery worker -l info
  271. .. topic:: Evolving the API
  272. Celery has changed a lot in the 3 years since it was initially
  273. created.
  274. For example, in the beginning it was possible to use any callable as
  275. a task:
  276. .. code-block:: python
  277. def hello(to):
  278. return 'hello {0}'.format(to)
  279. >>> from celery.execute import apply_async
  280. >>> apply_async(hello, ('world!', ))
  281. or you could also create a ``Task`` class to set
  282. certain options, or override other behavior
  283. .. code-block:: python
  284. from celery.task import Task
  285. from celery.registry import tasks
  286. class Hello(Task):
  287. send_error_emails = True
  288. def run(self, to):
  289. return 'hello {0}'.format(to)
  290. tasks.register(Hello)
  291. >>> Hello.delay('world!')
  292. Later, it was decided that passing arbitrary call-ables
  293. was an anti-pattern, since it makes it very hard to use
  294. serializers other than pickle, and the feature was removed
  295. in 2.0, replaced by task decorators:
  296. .. code-block:: python
  297. from celery.task import task
  298. @task(send_error_emails=True)
  299. def hello(x):
  300. return 'hello {0}'.format(to)
  301. Abstract Tasks
  302. ==============
  303. All tasks created using the :meth:`~@Celery.task` decorator
  304. will inherit from the applications base :attr:`~@Celery.Task` class.
  305. You can specify a different base class with the ``base`` argument:
  306. .. code-block:: python
  307. @app.task(base=OtherTask):
  308. def add(x, y):
  309. return x + y
  310. To create a custom task class you should inherit from the neutral base
  311. class: :class:`celery.Task`.
  312. .. code-block:: python
  313. from celery import Task
  314. class DebugTask(Task):
  315. abstract = True
  316. def __call__(self, *args, **kwargs):
  317. print('TASK STARTING: {0.name}[{0.request.id}]'.format(self))
  318. return super(DebugTask, self).__call__(*args, **kwargs)
  319. .. tip::
  320. If you override the tasks ``__call__`` method, then it's very important
  321. that you also call super so that the base call method can set up the
  322. default request used when a task is called directly.
  323. The neutral base class is special because it's not bound to any specific app
  324. yet. Concrete subclasses of this class will be bound, so you should
  325. always mark generic base classes as ``abstract``
  326. Once a task is bound to an app it will read configuration to set default values
  327. and so on.
  328. It's also possible to change the default base class for an application
  329. by changing its :meth:`@Celery.Task` attribute:
  330. .. code-block:: python
  331. >>> from celery import Celery, Task
  332. >>> app = Celery()
  333. >>> class MyBaseTask(Task):
  334. ... abstract = True
  335. ... send_error_emails = True
  336. >>> app.Task = MyBaseTask
  337. >>> app.Task
  338. <unbound MyBaseTask>
  339. >>> @x.task
  340. ... def add(x, y):
  341. ... return x + y
  342. >>> add
  343. <@task: __main__.add>
  344. >>> add.__class__.mro()
  345. [<class add of <Celery __main__:0x1012b4410>>,
  346. <unbound MyBaseTask>,
  347. <unbound Task>,
  348. <type 'object'>]