application.rst 14 KB

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