tasks.rst 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  1. .. _guide-tasks:
  2. =======
  3. Tasks
  4. =======
  5. Tasks are the building blocks of Celery applications.
  6. A task is a class that can be created out of any callable. It performs
  7. dual roles in that it defines both what happens when a task is
  8. called (sends a message), and what happens when a worker receives that message.
  9. Every task class has a unique name, and this name is referenced in messages
  10. so that the worker can find the right function to execute.
  11. A task message does not disappear
  12. until the message has been :term:`acknowledged` by a worker. A worker can reserve
  13. many messages in advance and even if the worker is killed -- caused by power failure
  14. or otherwise -- the message will be redelivered to another worker.
  15. Ideally task functions should be :term:`idempotent`, which means that
  16. the function will not cause unintended effects even if called
  17. multiple times with the same arguments.
  18. Since the worker cannot detect if your tasks are idempotent, the default
  19. behavior is to acknowledge the message in advance, before it's executed,
  20. so that a task that has already been started is never executed again..
  21. If your task is idempotent you can set the :attr:`acks_late` option
  22. to have the worker acknowledge the message *after* the task returns
  23. instead. See also the FAQ entry :ref:`faq-acks_late-vs-retry`.
  24. --
  25. In this chapter you will learn all about defining tasks,
  26. and this is the **table of contents**:
  27. .. contents::
  28. :local:
  29. :depth: 1
  30. .. _task-basics:
  31. Basics
  32. ======
  33. You can easily create a task from any callable by using
  34. the :meth:`~@task` decorator:
  35. .. code-block:: python
  36. from .models import User
  37. @app.task
  38. def create_user(username, password):
  39. User.objects.create(username=username, password=password)
  40. There are also many :ref:`options <task-options>` that can be set for the task,
  41. these can be specified as arguments to the decorator:
  42. .. code-block:: python
  43. @app.task(serializer='json')
  44. def create_user(username, password):
  45. User.objects.create(username=username, password=password)
  46. .. sidebar:: How do I import the task decorator? And what is "app"?
  47. The task decorator is available on your :class:`@Celery` application instance,
  48. if you don't know what that is then please read :ref:`first-steps`.
  49. If you're using Django or are still using the "old" module based celery API,
  50. then you can import the task decorator like this:
  51. .. code-block:: python
  52. from celery import task
  53. @task
  54. def add(x, y):
  55. return x + y
  56. .. sidebar:: Multiple decorators
  57. When using multiple decorators in combination with the task
  58. decorator you must make sure that the `task`
  59. decorator is applied last (which in Python oddly means that it must
  60. be the first in the list):
  61. .. code-block:: python
  62. @app.task
  63. @decorator2
  64. @decorator1
  65. def add(x, y):
  66. return x + y
  67. Bound tasks
  68. -----------
  69. A task being bound means the first argument to the task will always
  70. be the task instance (``self``), just like Python bound methods:
  71. .. code-block:: python
  72. logger = get_task_logger(__name__)
  73. @task(bind=True)
  74. def add(self, x, y):
  75. logger.info(self.request.id)
  76. Bound tasks are needed for retries (using :meth:`@Task.retry`), for
  77. accessing information about the current task request, and for any additional
  78. functionality you add to custom task base classes.
  79. Task inheritance
  80. ----------------
  81. The ``base`` argument to the task decorator specifies the base class of the task:
  82. .. code-block:: python
  83. import celery
  84. class MyTask(celery.Task):
  85. def on_failure(self, exc, task_id, args, kwargs, einfo):
  86. print('{0!r} failed: {1!r}'.format(task_id, exc)
  87. @task(base=MyTask)
  88. def add(x, y):
  89. raise KeyError()
  90. .. _task-names:
  91. Names
  92. =====
  93. Every task must have a unique name, and a new name
  94. will be generated out of the function name if a custom name is not provided.
  95. For example:
  96. .. code-block:: pycon
  97. >>> @app.task(name='sum-of-two-numbers')
  98. >>> def add(x, y):
  99. ... return x + y
  100. >>> add.name
  101. 'sum-of-two-numbers'
  102. A best practice is to use the module name as a name-space,
  103. this way names won't collide if there's already a task with that name
  104. defined in another module.
  105. .. code-block:: pycon
  106. >>> @app.task(name='tasks.add')
  107. >>> def add(x, y):
  108. ... return x + y
  109. You can tell the name of the task by investigating its name attribute:
  110. .. code-block:: pycon
  111. >>> add.name
  112. 'tasks.add'
  113. Which is exactly the name that would have been generated anyway,
  114. if the module name is :file:`tasks.py`:
  115. :file:`tasks.py`:
  116. .. code-block:: python
  117. @app.task
  118. def add(x, y):
  119. return x + y
  120. >>> from tasks import add
  121. >>> add.name
  122. 'tasks.add'
  123. .. _task-naming-relative-imports:
  124. Automatic naming and relative imports
  125. -------------------------------------
  126. Relative imports and automatic name generation do not go well together,
  127. so if you're using relative imports you should set the name explicitly.
  128. For example if the client imports the module ``"myapp.tasks"``
  129. as ``".tasks"``, and the worker imports the module as ``"myapp.tasks"``,
  130. the generated names won't match and an :exc:`~@NotRegistered` error will
  131. be raised by the worker.
  132. This is also the case when using Django and using ``project.myapp``-style
  133. naming in ``INSTALLED_APPS``:
  134. .. code-block:: python
  135. INSTALLED_APPS = ['project.myapp']
  136. If you install the app under the name ``project.myapp`` then the
  137. tasks module will be imported as ``project.myapp.tasks``,
  138. so you must make sure you always import the tasks using the same name:
  139. .. code-block:: pycon
  140. >>> from project.myapp.tasks import mytask # << GOOD
  141. >>> from myapp.tasks import mytask # << BAD!!!
  142. The second example will cause the task to be named differently
  143. since the worker and the client imports the modules under different names:
  144. .. code-block:: pycon
  145. >>> from project.myapp.tasks import mytask
  146. >>> mytask.name
  147. 'project.myapp.tasks.mytask'
  148. >>> from myapp.tasks import mytask
  149. >>> mytask.name
  150. 'myapp.tasks.mytask'
  151. So for this reason you must be consistent in how you
  152. import modules, which is also a Python best practice.
  153. Similarly, you should not use old-style relative imports:
  154. .. code-block:: python
  155. from module import foo # BAD!
  156. from proj.module import foo # GOOD!
  157. New-style relative imports are fine and can be used:
  158. .. code-block:: python
  159. from .module import foo # GOOD!
  160. If you want to use Celery with a project already using these patterns
  161. extensively and you don't have the time to refactor the existing code
  162. then you can consider specifying the names explicitly instead of relying
  163. on the automatic naming:
  164. .. code-block:: python
  165. @task(name='proj.tasks.add')
  166. def add(x, y):
  167. return x + y
  168. .. _task-name-generator-info:
  169. Changing the automatic naming behavior
  170. --------------------------------------
  171. .. versionadded:: 4.0
  172. There are some cases when the default automatic naming is not suitable.
  173. Consider you have many tasks within many different modules::
  174. project/
  175. /__init__.py
  176. /celery.py
  177. /moduleA/
  178. /__init__.py
  179. /tasks.py
  180. /moduleB/
  181. /__init__.py
  182. /tasks.py
  183. Using the default automatic naming, each task will have a generated name
  184. like `moduleA.tasks.taskA`, `moduleA.tasks.taskB`, `moduleB.tasks.test`
  185. and so on. You may want to get rid of having `tasks` in all task names.
  186. As pointed above, you can explicitly give names for all tasks, or you
  187. can change the automatic naming behavior by overriding
  188. :meth:`@gen_task_name`. Continuing with the example, `celery.py`
  189. may contain:
  190. .. code-block:: python
  191. from celery import Celery
  192. class MyCelery(Celery):
  193. def gen_task_name(self, name, module):
  194. if module.endswith('.tasks'):
  195. module = module[:-6]
  196. return super(MyCelery, self).gen_task_name(name, module)
  197. app = MyCelery('main')
  198. So each task will have a name like `moduleA.taskA`, `moduleA.taskB` and
  199. `moduleB.test`.
  200. .. warning::
  201. Make sure that your :meth:`@gen_task_name` is a pure function, which means
  202. that for the same input it must always return the same output.
  203. .. _task-request-info:
  204. Context
  205. =======
  206. :attr:`~@Task.request` contains information and state related to
  207. the executing task.
  208. The request defines the following attributes:
  209. :id: The unique id of the executing task.
  210. :group: The unique id of the task's :ref:`group <canvas-group>`, if this task is a member.
  211. :chord: The unique id of the chord this task belongs to (if the task
  212. is part of the header).
  213. :args: Positional arguments.
  214. :kwargs: Keyword arguments.
  215. :retries: How many times the current task has been retried.
  216. An integer starting at `0`.
  217. :is_eager: Set to :const:`True` if the task is executed locally in
  218. the client, and not by a worker.
  219. :eta: The original ETA of the task (if any).
  220. This is in UTC time (depending on the :setting:`enable_utc`
  221. setting).
  222. :expires: The original expiry time of the task (if any).
  223. This is in UTC time (depending on the :setting:`enable_utc`
  224. setting).
  225. :logfile: The file the worker logs to. See `Logging`_.
  226. :loglevel: The current log level used.
  227. :hostname: Node name of the worker instance executing the task.
  228. :delivery_info: Additional message delivery information. This is a mapping
  229. containing the exchange and routing key used to deliver this
  230. task. Used by e.g. :meth:`~@Task.retry`
  231. to resend the task to the same destination queue.
  232. Availability of keys in this dict depends on the
  233. message broker used.
  234. :called_directly: This flag is set to true if the task was not
  235. executed by the worker.
  236. :callbacks: A list of signatures to be called if this task returns successfully.
  237. :errback: A list of signatures to be called if this task fails.
  238. :utc: Set to true the caller has UTC enabled (:setting:`enable_utc`).
  239. .. versionadded:: 3.1
  240. :headers: Mapping of message headers (may be :const:`None`).
  241. :reply_to: Where to send reply to (queue name).
  242. :correlation_id: Usually the same as the task id, often used in amqp
  243. to keep track of what a reply is for.
  244. An example task accessing information in the context is:
  245. .. code-block:: python
  246. @app.task(bind=True)
  247. def dump_context(self, x, y):
  248. print('Executing task id {0.id}, args: {0.args!r} kwargs: {0.kwargs!r}'.format(
  249. self.request))
  250. The ``bind`` argument means that the function will be a "bound method" so
  251. that you can access attributes and methods on the task type instance.
  252. .. _task-logging:
  253. Logging
  254. =======
  255. The worker will automatically set up logging for you, or you can
  256. configure logging manually.
  257. A special logger is available named "celery.task", you can inherit
  258. from this logger to automatically get the task name and unique id as part
  259. of the logs.
  260. The best practice is to create a common logger
  261. for all of your tasks at the top of your module:
  262. .. code-block:: python
  263. from celery.utils.log import get_task_logger
  264. logger = get_task_logger(__name__)
  265. @app.task
  266. def add(x, y):
  267. logger.info('Adding {0} + {1}'.format(x, y))
  268. return x + y
  269. Celery uses the standard Python logger library,
  270. for which documentation can be found in the :mod:`logging`
  271. module.
  272. You can also use :func:`print`, as anything written to standard
  273. out/-err will be redirected to the logging system (you can disable this,
  274. see :setting:`worker_redirect_stdouts`).
  275. .. note::
  276. The worker will not update the redirection if you create a logger instance
  277. somewhere in your task or task module.
  278. If you want to redirect ``sys.stdout`` and ``sys.stderr`` to a custom
  279. logger you have to enable this manually, for example:
  280. .. code-block:: python
  281. import sys
  282. logger = get_task_logger(__name__)
  283. @app.task(bind=True)
  284. def add(self, x, y):
  285. old_outs = sys.stdout, sys.stderr
  286. rlevel = self.app.conf.worker_redirect_stdouts_level
  287. try:
  288. self.app.log.redirect_stdouts_to_logger(logger, rlevel)
  289. print('Adding {0} + {1}'.format(x, y))
  290. return x + y
  291. finally:
  292. sys.stdout, sys.stderr = old_outs
  293. .. _task-retry:
  294. Retrying
  295. ========
  296. :meth:`~@Task.retry` can be used to re-execute the task,
  297. for example in the event of recoverable errors.
  298. When you call ``retry`` it will send a new message, using the same
  299. task-id, and it will take care to make sure the message is delivered
  300. to the same queue as the originating task.
  301. When a task is retried this is also recorded as a task state,
  302. so that you can track the progress of the task using the result
  303. instance (see :ref:`task-states`).
  304. Here's an example using ``retry``:
  305. .. code-block:: python
  306. @app.task(bind=True)
  307. def send_twitter_status(self, oauth, tweet):
  308. try:
  309. twitter = Twitter(oauth)
  310. twitter.update_status(tweet)
  311. except (Twitter.FailWhaleError, Twitter.LoginError) as exc:
  312. raise self.retry(exc=exc)
  313. .. note::
  314. The :meth:`~@Task.retry` call will raise an exception so any code after the retry
  315. will not be reached. This is the :exc:`~@Retry`
  316. exception, it is not handled as an error but rather as a semi-predicate
  317. to signify to the worker that the task is to be retried,
  318. so that it can store the correct state when a result backend is enabled.
  319. This is normal operation and always happens unless the
  320. ``throw`` argument to retry is set to :const:`False`.
  321. The bind argument to the task decorator will give access to ``self`` (the
  322. task type instance).
  323. The ``exc`` method is used to pass exception information that is
  324. used in logs, and when storing task results.
  325. Both the exception and the traceback will
  326. be available in the task state (if a result backend is enabled).
  327. If the task has a ``max_retries`` value the current exception
  328. will be re-raised if the max number of retries has been exceeded,
  329. but this will not happen if:
  330. - An ``exc`` argument was not given.
  331. In this case the :exc:`~@MaxRetriesExceededError`
  332. exception will be raised.
  333. - There is no current exception
  334. If there's no original exception to re-raise the ``exc``
  335. argument will be used instead, so:
  336. .. code-block:: python
  337. self.retry(exc=Twitter.LoginError())
  338. will raise the ``exc`` argument given.
  339. .. _task-retry-custom-delay:
  340. Using a custom retry delay
  341. --------------------------
  342. When a task is to be retried, it can wait for a given amount of time
  343. before doing so, and the default delay is defined by the
  344. :attr:`~@Task.default_retry_delay`
  345. attribute. By default this is set to 3 minutes. Note that the
  346. unit for setting the delay is in seconds (int or float).
  347. You can also provide the `countdown` argument to :meth:`~@Task.retry` to
  348. override this default.
  349. .. code-block:: python
  350. @app.task(bind=True, default_retry_delay=30 * 60) # retry in 30 minutes.
  351. def add(self, x, y):
  352. try:
  353. something_raising()
  354. except Exception as exc:
  355. # overrides the default delay to retry after 1 minute
  356. raise self.retry(exc=exc, countdown=60)
  357. .. _task-autoretry:
  358. Automatic retry for known exceptions
  359. ------------------------------------
  360. .. versionadded:: 4.0
  361. Sometimes you just want to retry a task whenever a particular exception
  362. is raised.
  363. As this is such a common pattern we have built-in support for it
  364. with the
  365. This may not be acceptable all the time, since you may have a lot of such
  366. tasks.
  367. Fortunately, you can tell Celery to automatically retry a task using
  368. `autoretry_for` argument in `~@Celery.task` decorator:
  369. .. code-block:: python
  370. from twitter.exceptions import FailWhaleError
  371. @app.task(autoretry_for=(FailWhaleError,))
  372. def refresh_timeline(user):
  373. return twitter.refresh_timeline(user)
  374. If you want to specify custom arguments for internal `~@Task.retry`
  375. call, pass `retry_kwargs` argument to `~@Celery.task` decorator:
  376. .. code-block:: python
  377. @app.task(autoretry_for=(FailWhaleError,),
  378. retry_kwargs={'max_retries': 5})
  379. def refresh_timeline(user):
  380. return twitter.refresh_timeline(user)
  381. This is provided as an alternative to manually handling the exceptions,
  382. and the example above will do the same as wrapping the task body
  383. in a :keyword:`try` ... :keyword:`except` statement, i.e.:
  384. .. code-block:: python
  385. @app.task
  386. def refresh_timeline(user):
  387. try:
  388. twitter.refresh_timeline(user)
  389. except FailWhaleError as exc:
  390. raise div.retry(exc=exc, max_retries=5)
  391. .. _task-options:
  392. List of Options
  393. ===============
  394. The task decorator can take a number of options that change the way
  395. the task behaves, for example you can set the rate limit for a task
  396. using the :attr:`rate_limit` option.
  397. Any keyword argument passed to the task decorator will actually be set
  398. as an attribute of the resulting task class, and this is a list
  399. of the built-in attributes.
  400. General
  401. -------
  402. .. _task-general-options:
  403. .. attribute:: Task.name
  404. The name the task is registered as.
  405. You can set this name manually, or a name will be
  406. automatically generated using the module and class name. See
  407. :ref:`task-names`.
  408. .. attribute:: Task.request
  409. If the task is being executed this will contain information
  410. about the current request. Thread local storage is used.
  411. See :ref:`task-request-info`.
  412. .. attribute:: Task.abstract
  413. Abstract classes are not registered, but are used as the
  414. base class for new task types.
  415. .. attribute:: Task.max_retries
  416. The maximum number of attempted retries before giving up.
  417. If the number of retries exceeds this value a :exc:`~@MaxRetriesExceededError`
  418. exception will be raised. *NOTE:* You have to call :meth:`~@Task.retry`
  419. manually, as it will not automatically retry on exception..
  420. The default value is 3.
  421. A value of :const:`None` will disable the retry limit and the
  422. task will retry forever until it succeeds.
  423. .. attribute:: Task.throws
  424. Optional tuple of expected error classes that should not be regarded
  425. as an actual error.
  426. Errors in this list will be reported as a failure to the result backend,
  427. but the worker will not log the event as an error, and no traceback will
  428. be included.
  429. Example:
  430. .. code-block:: python
  431. @task(throws=(KeyError, HttpNotFound)):
  432. def get_foo():
  433. something()
  434. Error types:
  435. - Expected errors (in ``Task.throws``)
  436. Logged with severity ``INFO``, traceback excluded.
  437. - Unexpected errors
  438. Logged with severity ``ERROR``, with traceback included.
  439. .. attribute:: Task.default_retry_delay
  440. Default time in seconds before a retry of the task
  441. should be executed. Can be either :class:`int` or :class:`float`.
  442. Default is a 3 minute delay.
  443. .. attribute:: Task.rate_limit
  444. Set the rate limit for this task type which limits the number of tasks
  445. that can be run in a given time frame. Tasks will still complete when
  446. a rate limit is in effect, but it may take some time before it's allowed to
  447. start.
  448. If this is :const:`None` no rate limit is in effect.
  449. If it is an integer or float, it is interpreted as "tasks per second".
  450. The rate limits can be specified in seconds, minutes or hours
  451. by appending `"/s"`, `"/m"` or `"/h"` to the value. Tasks will be evenly
  452. distributed over the specified time frame.
  453. Example: `"100/m"` (hundred tasks a minute). This will enforce a minimum
  454. delay of 600ms between starting two tasks on the same worker instance.
  455. Default is the :setting:`task_default_rate_limit` setting,
  456. which if not specified means rate limiting for tasks is disabled by default.
  457. Note that this is a *per worker instance* rate limit, and not a global
  458. rate limit. To enforce a global rate limit (e.g. for an API with a
  459. maximum number of requests per second), you must restrict to a given
  460. queue.
  461. .. attribute:: Task.time_limit
  462. The hard time limit, in seconds, for this task. If not set then the workers default
  463. will be used.
  464. .. attribute:: Task.soft_time_limit
  465. The soft time limit for this task. If not set then the workers default
  466. will be used.
  467. .. attribute:: Task.ignore_result
  468. Don't store task state. Note that this means you can't use
  469. :class:`~celery.result.AsyncResult` to check if the task is ready,
  470. or get its return value.
  471. .. attribute:: Task.store_errors_even_if_ignored
  472. If :const:`True`, errors will be stored even if the task is configured
  473. to ignore results.
  474. .. attribute:: Task.send_error_emails
  475. Send an email whenever a task of this type fails.
  476. Defaults to the :setting:`task_send_error_emails` setting.
  477. See :ref:`conf-error-mails` for more information.
  478. .. attribute:: Task.ErrorMail
  479. If the sending of error emails is enabled for this task, then
  480. this is the class defining the logic to send error mails.
  481. .. attribute:: Task.serializer
  482. A string identifying the default serialization
  483. method to use. Defaults to the :setting:`task_serializer`
  484. setting. Can be `pickle`, `json`, `yaml`, or any custom
  485. serialization methods that have been registered with
  486. :mod:`kombu.serialization.registry`.
  487. Please see :ref:`calling-serializers` for more information.
  488. .. attribute:: Task.compression
  489. A string identifying the default compression scheme to use.
  490. Defaults to the :setting:`task_compression` setting.
  491. Can be `gzip`, or `bzip2`, or any custom compression schemes
  492. that have been registered with the :mod:`kombu.compression` registry.
  493. Please see :ref:`calling-compression` for more information.
  494. .. attribute:: Task.backend
  495. The result store backend to use for this task. An instance of one of the
  496. backend classes in `celery.backends`. Defaults to `app.backend` which is
  497. defined by the :setting:`result_backend` setting.
  498. .. attribute:: Task.acks_late
  499. If set to :const:`True` messages for this task will be acknowledged
  500. **after** the task has been executed, not *just before*, which is
  501. the default behavior.
  502. Note that this means the task may be executed twice if the worker
  503. crashes in the middle of execution, which may be acceptable for some
  504. applications.
  505. The global default can be overridden by the :setting:`task_acks_late`
  506. setting.
  507. .. _task-track-started:
  508. .. attribute:: Task.track_started
  509. If :const:`True` the task will report its status as "started"
  510. when the task is executed by a worker.
  511. The default value is :const:`False` as the normal behavior is to not
  512. report that level of granularity. Tasks are either pending, finished,
  513. or waiting to be retried. Having a "started" status can be useful for
  514. when there are long running tasks and there is a need to report which
  515. task is currently running.
  516. The host name and process id of the worker executing the task
  517. will be available in the state meta-data (e.g. `result.info['pid']`)
  518. The global default can be overridden by the
  519. :setting:`task_track_started` setting.
  520. .. seealso::
  521. The API reference for :class:`~@Task`.
  522. .. _task-states:
  523. States
  524. ======
  525. Celery can keep track of the tasks current state. The state also contains the
  526. result of a successful task, or the exception and traceback information of a
  527. failed task.
  528. There are several *result backends* to choose from, and they all have
  529. different strengths and weaknesses (see :ref:`task-result-backends`).
  530. During its lifetime a task will transition through several possible states,
  531. and each state may have arbitrary meta-data attached to it. When a task
  532. moves into a new state the previous state is
  533. forgotten about, but some transitions can be deducted, (e.g. a task now
  534. in the :state:`FAILED` state, is implied to have been in the
  535. :state:`STARTED` state at some point).
  536. There are also sets of states, like the set of
  537. :state:`FAILURE_STATES`, and the set of :state:`READY_STATES`.
  538. The client uses the membership of these sets to decide whether
  539. the exception should be re-raised (:state:`PROPAGATE_STATES`), or whether
  540. the state can be cached (it can if the task is ready).
  541. You can also define :ref:`custom-states`.
  542. .. _task-result-backends:
  543. Result Backends
  544. ---------------
  545. If you want to keep track of tasks or need the return values, then Celery
  546. must store or send the states somewhere so that they can be retrieved later.
  547. There are several built-in result backends to choose from: SQLAlchemy/Django ORM,
  548. Memcached, RabbitMQ/QPid (``rpc``), MongoDB, and Redis -- or you can define your own.
  549. No backend works well for every use case.
  550. You should read about the strengths and weaknesses of each backend, and choose
  551. the most appropriate for your needs.
  552. .. seealso::
  553. :ref:`conf-result-backend`
  554. RPC Result Backend (RabbitMQ/QPid)
  555. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  556. The RPC result backend (`rpc://`) is special as it does not actually *store*
  557. the states, but rather sends them as messages. This is an important difference as it
  558. means that a result *can only be retrieved once*, and *only by the client
  559. that initiated the task*. Two different processes can not wait for the same result.
  560. Even with that limitation, it is an excellent choice if you need to receive
  561. state changes in real-time. Using messaging means the client does not have to
  562. poll for new states.
  563. The messages are transient (non-persistent) by default, so the results will
  564. disappear if the broker restarts. You can configure the result backend to send
  565. persistent messages using the :setting:`result_persistent` setting.
  566. Database Result Backend
  567. ~~~~~~~~~~~~~~~~~~~~~~~
  568. Keeping state in the database can be convenient for many, especially for
  569. web applications with a database already in place, but it also comes with
  570. limitations.
  571. * Polling the database for new states is expensive, and so you should
  572. increase the polling intervals of operations such as `result.get()`.
  573. * Some databases use a default transaction isolation level that
  574. is not suitable for polling tables for changes.
  575. In MySQL the default transaction isolation level is `REPEATABLE-READ`, which
  576. means the transaction will not see changes by other transactions until the
  577. transaction is committed. It is recommended that you change to the
  578. `READ-COMMITTED` isolation level.
  579. .. _task-builtin-states:
  580. Built-in States
  581. ---------------
  582. .. state:: PENDING
  583. PENDING
  584. ~~~~~~~
  585. Task is waiting for execution or unknown.
  586. Any task id that is not known is implied to be in the pending state.
  587. .. state:: STARTED
  588. STARTED
  589. ~~~~~~~
  590. Task has been started.
  591. Not reported by default, to enable please see :attr:`@Task.track_started`.
  592. :meta-data: `pid` and `hostname` of the worker process executing
  593. the task.
  594. .. state:: SUCCESS
  595. SUCCESS
  596. ~~~~~~~
  597. Task has been successfully executed.
  598. :meta-data: `result` contains the return value of the task.
  599. :propagates: Yes
  600. :ready: Yes
  601. .. state:: FAILURE
  602. FAILURE
  603. ~~~~~~~
  604. Task execution resulted in failure.
  605. :meta-data: `result` contains the exception occurred, and `traceback`
  606. contains the backtrace of the stack at the point when the
  607. exception was raised.
  608. :propagates: Yes
  609. .. state:: RETRY
  610. RETRY
  611. ~~~~~
  612. Task is being retried.
  613. :meta-data: `result` contains the exception that caused the retry,
  614. and `traceback` contains the backtrace of the stack at the point
  615. when the exceptions was raised.
  616. :propagates: No
  617. .. state:: REVOKED
  618. REVOKED
  619. ~~~~~~~
  620. Task has been revoked.
  621. :propagates: Yes
  622. .. _custom-states:
  623. Custom states
  624. -------------
  625. You can easily define your own states, all you need is a unique name.
  626. The name of the state is usually an uppercase string. As an example
  627. you could have a look at :mod:`abortable tasks <~celery.contrib.abortable>`
  628. which defines its own custom :state:`ABORTED` state.
  629. Use :meth:`~@Task.update_state` to update a task's state:.
  630. .. code-block:: python
  631. @app.task(bind=True)
  632. def upload_files(self, filenames):
  633. for i, file in enumerate(filenames):
  634. if not self.request.called_directly:
  635. self.update_state(state='PROGRESS',
  636. meta={'current': i, 'total': len(filenames)})
  637. Here I created the state `"PROGRESS"`, which tells any application
  638. aware of this state that the task is currently in progress, and also where
  639. it is in the process by having `current` and `total` counts as part of the
  640. state meta-data. This can then be used to create e.g. progress bars.
  641. .. _pickling_exceptions:
  642. Creating pickleable exceptions
  643. ------------------------------
  644. A rarely known Python fact is that exceptions must conform to some
  645. simple rules to support being serialized by the pickle module.
  646. Tasks that raise exceptions that are not pickleable will not work
  647. properly when Pickle is used as the serializer.
  648. To make sure that your exceptions are pickleable the exception
  649. *MUST* provide the original arguments it was instantiated
  650. with in its ``.args`` attribute. The simplest way
  651. to ensure this is to have the exception call ``Exception.__init__``.
  652. Let's look at some examples that work, and one that doesn't:
  653. .. code-block:: python
  654. # OK:
  655. class HttpError(Exception):
  656. pass
  657. # BAD:
  658. class HttpError(Exception):
  659. def __init__(self, status_code):
  660. self.status_code = status_code
  661. # OK:
  662. class HttpError(Exception):
  663. def __init__(self, status_code):
  664. self.status_code = status_code
  665. Exception.__init__(self, status_code) # <-- REQUIRED
  666. So the rule is:
  667. For any exception that supports custom arguments ``*args``,
  668. ``Exception.__init__(self, *args)`` must be used.
  669. There is no special support for *keyword arguments*, so if you
  670. want to preserve keyword arguments when the exception is unpickled
  671. you have to pass them as regular args:
  672. .. code-block:: python
  673. class HttpError(Exception):
  674. def __init__(self, status_code, headers=None, body=None):
  675. self.status_code = status_code
  676. self.headers = headers
  677. self.body = body
  678. super(HttpError, self).__init__(status_code, headers, body)
  679. .. _task-semipredicates:
  680. Semipredicates
  681. ==============
  682. The worker wraps the task in a tracing function which records the final
  683. state of the task. There are a number of exceptions that can be used to
  684. signal this function to change how it treats the return of the task.
  685. .. _task-semipred-ignore:
  686. Ignore
  687. ------
  688. The task may raise :exc:`~@Ignore` to force the worker to ignore the
  689. task. This means that no state will be recorded for the task, but the
  690. message is still acknowledged (removed from queue).
  691. This can be used if you want to implement custom revoke-like
  692. functionality, or manually store the result of a task.
  693. Example keeping revoked tasks in a Redis set:
  694. .. code-block:: python
  695. from celery.exceptions import Ignore
  696. @app.task(bind=True)
  697. def some_task(self):
  698. if redis.ismember('tasks.revoked', self.request.id):
  699. raise Ignore()
  700. Example that stores results manually:
  701. .. code-block:: python
  702. from celery import states
  703. from celery.exceptions import Ignore
  704. @app.task(bind=True)
  705. def get_tweets(self, user):
  706. timeline = twitter.get_timeline(user)
  707. if not self.request.called_directly:
  708. self.update_state(state=states.SUCCESS, meta=timeline)
  709. raise Ignore()
  710. .. _task-semipred-reject:
  711. Reject
  712. ------
  713. The task may raise :exc:`~@Reject` to reject the task message using
  714. AMQPs ``basic_reject`` method. This will not have any effect unless
  715. :attr:`Task.acks_late` is enabled.
  716. Rejecting a message has the same effect as acking it, but some
  717. brokers may implement additional functionality that can be used.
  718. For example RabbitMQ supports the concept of `Dead Letter Exchanges`_
  719. where a queue can be configured to use a dead letter exchange that rejected
  720. messages are redelivered to.
  721. .. _`Dead Letter Exchanges`: http://www.rabbitmq.com/dlx.html
  722. Reject can also be used to re-queue messages, but please be very careful
  723. when using this as it can easily result in an infinite message loop.
  724. Example using reject when a task causes an out of memory condition:
  725. .. code-block:: python
  726. import errno
  727. from celery.exceptions import Reject
  728. @app.task(bind=True, acks_late=True)
  729. def render_scene(self, path):
  730. file = get_file(path)
  731. try:
  732. renderer.render_scene(file)
  733. # if the file is too big to fit in memory
  734. # we reject it so that it's redelivered to the dead letter exchange
  735. # and we can manually inspect the situation.
  736. except MemoryError as exc:
  737. raise Reject(exc, requeue=False)
  738. except OSError as exc:
  739. if exc.errno == errno.ENOMEM:
  740. raise Reject(exc, requeue=False)
  741. # For any other error we retry after 10 seconds.
  742. except Exception as exc:
  743. raise self.retry(exc, countdown=10)
  744. Example requeueing the message:
  745. .. code-block:: python
  746. from celery.exceptions import Reject
  747. @app.task(bind=True, acks_late=True)
  748. def requeues(self):
  749. if not self.request.delivery_info['redelivered']:
  750. raise Reject('no reason', requeue=True)
  751. print('received two times')
  752. Consult your broker documentation for more details about the ``basic_reject``
  753. method.
  754. .. _task-semipred-retry:
  755. Retry
  756. -----
  757. The :exc:`~@Retry` exception is raised by the ``Task.retry`` method
  758. to tell the worker that the task is being retried.
  759. .. _task-custom-classes:
  760. Custom task classes
  761. ===================
  762. All tasks inherit from the :class:`@Task` class.
  763. The :meth:`~@Task.run` method becomes the task body.
  764. As an example, the following code,
  765. .. code-block:: python
  766. @app.task
  767. def add(x, y):
  768. return x + y
  769. will do roughly this behind the scenes:
  770. .. code-block:: python
  771. class _AddTask(app.Task):
  772. def run(self, x, y):
  773. return x + y
  774. add = app.tasks[_AddTask.name]
  775. Instantiation
  776. -------------
  777. A task is **not** instantiated for every request, but is registered
  778. in the task registry as a global instance.
  779. This means that the ``__init__`` constructor will only be called
  780. once per process, and that the task class is semantically closer to an
  781. Actor.
  782. If you have a task,
  783. .. code-block:: python
  784. from celery import Task
  785. class NaiveAuthenticateServer(Task):
  786. def __init__(self):
  787. self.users = {'george': 'password'}
  788. def run(self, username, password):
  789. try:
  790. return self.users[username] == password
  791. except KeyError:
  792. return False
  793. And you route every request to the same process, then it
  794. will keep state between requests.
  795. This can also be useful to cache resources,
  796. e.g. a base Task class that caches a database connection:
  797. .. code-block:: python
  798. from celery import Task
  799. class DatabaseTask(Task):
  800. abstract = True
  801. _db = None
  802. @property
  803. def db(self):
  804. if self._db is None:
  805. self._db = Database.connect()
  806. return self._db
  807. that can be added to tasks like this:
  808. .. code-block:: python
  809. @app.task(base=DatabaseTask)
  810. def process_rows():
  811. for row in process_rows.db.table.all():
  812. process_row(row)
  813. The ``db`` attribute of the ``process_rows`` task will then
  814. always stay the same in each process.
  815. Abstract classes
  816. ----------------
  817. Abstract classes are not registered, but are used as the
  818. base class for new task types.
  819. .. code-block:: python
  820. from celery import Task
  821. class DebugTask(Task):
  822. abstract = True
  823. def after_return(self, *args, **kwargs):
  824. print('Task returned: {0!r}'.format(self.request))
  825. @app.task(base=DebugTask)
  826. def add(x, y):
  827. return x + y
  828. Handlers
  829. --------
  830. .. method:: after_return(self, status, retval, task_id, args, kwargs, einfo)
  831. Handler called after the task returns.
  832. :param status: Current task state.
  833. :param retval: Task return value/exception.
  834. :param task_id: Unique id of the task.
  835. :param args: Original arguments for the task that returned.
  836. :param kwargs: Original keyword arguments for the task
  837. that returned.
  838. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  839. instance, containing the traceback (if any).
  840. The return value of this handler is ignored.
  841. .. method:: on_failure(self, exc, task_id, args, kwargs, einfo)
  842. This is run by the worker when the task fails.
  843. :param exc: The exception raised by the task.
  844. :param task_id: Unique id of the failed task.
  845. :param args: Original arguments for the task that failed.
  846. :param kwargs: Original keyword arguments for the task
  847. that failed.
  848. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  849. instance, containing the traceback.
  850. The return value of this handler is ignored.
  851. .. method:: on_retry(self, exc, task_id, args, kwargs, einfo)
  852. This is run by the worker when the task is to be retried.
  853. :param exc: The exception sent to :meth:`~@Task.retry`.
  854. :param task_id: Unique id of the retried task.
  855. :param args: Original arguments for the retried task.
  856. :param kwargs: Original keyword arguments for the retried task.
  857. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  858. instance, containing the traceback.
  859. The return value of this handler is ignored.
  860. .. method:: on_success(self, retval, task_id, args, kwargs)
  861. Run by the worker if the task executes successfully.
  862. :param retval: The return value of the task.
  863. :param task_id: Unique id of the executed task.
  864. :param args: Original arguments for the executed task.
  865. :param kwargs: Original keyword arguments for the executed task.
  866. The return value of this handler is ignored.
  867. .. _task-how-they-work:
  868. How it works
  869. ============
  870. Here come the technical details. This part isn't something you need to know,
  871. but you may be interested.
  872. All defined tasks are listed in a registry. The registry contains
  873. a list of task names and their task classes. You can investigate this registry
  874. yourself:
  875. .. code-block:: pycon
  876. >>> from proj.celery import app
  877. >>> app.tasks
  878. {'celery.chord_unlock':
  879. <@task: celery.chord_unlock>,
  880. 'celery.backend_cleanup':
  881. <@task: celery.backend_cleanup>,
  882. 'celery.chord':
  883. <@task: celery.chord>}
  884. This is the list of tasks built-in to celery. Note that tasks
  885. will only be registered when the module they are defined in is imported.
  886. The default loader imports any modules listed in the
  887. :setting:`imports` setting.
  888. The entity responsible for registering your task in the registry is the
  889. meta-class: :class:`~celery.task.base.TaskType`.
  890. If you want to register your task manually you can mark the
  891. task as :attr:`~@Task.abstract`:
  892. .. code-block:: python
  893. class MyTask(Task):
  894. abstract = True
  895. This way the task won't be registered, but any task inheriting from
  896. it will be.
  897. When tasks are sent, no actual function code is sent with it, just the name
  898. of the task to execute. When the worker then receives the message it can look
  899. up the name in its task registry to find the execution code.
  900. This means that your workers should always be updated with the same software
  901. as the client. This is a drawback, but the alternative is a technical
  902. challenge that has yet to be solved.
  903. .. _task-best-practices:
  904. Tips and Best Practices
  905. =======================
  906. .. _task-ignore_results:
  907. Ignore results you don't want
  908. -----------------------------
  909. If you don't care about the results of a task, be sure to set the
  910. :attr:`~@Task.ignore_result` option, as storing results
  911. wastes time and resources.
  912. .. code-block:: python
  913. @app.task(ignore_result=True)
  914. def mytask():
  915. something()
  916. Results can even be disabled globally using the :setting:`task_ignore_result`
  917. setting.
  918. .. _task-disable-rate-limits:
  919. Disable rate limits if they're not used
  920. ---------------------------------------
  921. Disabling rate limits altogether is recommended if you don't have
  922. any tasks using them. This is because the rate limit subsystem introduces
  923. quite a lot of complexity.
  924. Set the :setting:`worker_disable_rate_limits` setting to globally disable
  925. rate limits:
  926. .. code-block:: python
  927. worker_disable_rate_limits = True
  928. You find additional optimization tips in the
  929. :ref:`Optimizing Guide <guide-optimizing>`.
  930. .. _task-synchronous-subtasks:
  931. Avoid launching synchronous subtasks
  932. ------------------------------------
  933. Having a task wait for the result of another task is really inefficient,
  934. and may even cause a deadlock if the worker pool is exhausted.
  935. Make your design asynchronous instead, for example by using *callbacks*.
  936. **Bad**:
  937. .. code-block:: python
  938. @app.task
  939. def update_page_info(url):
  940. page = fetch_page.delay(url).get()
  941. info = parse_page.delay(url, page).get()
  942. store_page_info.delay(url, info)
  943. @app.task
  944. def fetch_page(url):
  945. return myhttplib.get(url)
  946. @app.task
  947. def parse_page(url, page):
  948. return myparser.parse_document(page)
  949. @app.task
  950. def store_page_info(url, info):
  951. return PageInfo.objects.create(url, info)
  952. **Good**:
  953. .. code-block:: python
  954. def update_page_info(url):
  955. # fetch_page -> parse_page -> store_page
  956. chain = fetch_page.s(url) | parse_page.s() | store_page_info.s(url)
  957. chain()
  958. @app.task()
  959. def fetch_page(url):
  960. return myhttplib.get(url)
  961. @app.task()
  962. def parse_page(page):
  963. return myparser.parse_document(page)
  964. @app.task(ignore_result=True)
  965. def store_page_info(info, url):
  966. PageInfo.objects.create(url=url, info=info)
  967. Here I instead created a chain of tasks by linking together
  968. different :func:`~celery.signature`'s.
  969. You can read about chains and other powerful constructs
  970. at :ref:`designing-workflows`.
  971. .. _task-performance-and-strategies:
  972. Performance and Strategies
  973. ==========================
  974. .. _task-granularity:
  975. Granularity
  976. -----------
  977. The task granularity is the amount of computation needed by each subtask.
  978. In general it is better to split the problem up into many small tasks rather
  979. than have a few long running tasks.
  980. With smaller tasks you can process more tasks in parallel and the tasks
  981. won't run long enough to block the worker from processing other waiting tasks.
  982. However, executing a task does have overhead. A message needs to be sent, data
  983. may not be local, etc. So if the tasks are too fine-grained the additional
  984. overhead may not be worth it in the end.
  985. .. seealso::
  986. The book `Art of Concurrency`_ has a section dedicated to the topic
  987. of task granularity [AOC1]_.
  988. .. _`Art of Concurrency`: http://oreilly.com/catalog/9780596521547
  989. .. [AOC1] Breshears, Clay. Section 2.2.1, "The Art of Concurrency".
  990. O'Reilly Media, Inc. May 15, 2009. ISBN-13 978-0-596-52153-0.
  991. .. _task-data-locality:
  992. Data locality
  993. -------------
  994. The worker processing the task should be as close to the data as
  995. possible. The best would be to have a copy in memory, the worst would be a
  996. full transfer from another continent.
  997. If the data is far away, you could try to run another worker at location, or
  998. if that's not possible - cache often used data, or preload data you know
  999. is going to be used.
  1000. The easiest way to share data between workers is to use a distributed cache
  1001. system, like `memcached`_.
  1002. .. seealso::
  1003. The paper `Distributed Computing Economics`_ by Jim Gray is an excellent
  1004. introduction to the topic of data locality.
  1005. .. _`Distributed Computing Economics`:
  1006. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  1007. .. _`memcached`: http://memcached.org/
  1008. .. _task-state:
  1009. State
  1010. -----
  1011. Since celery is a distributed system, you can't know in which process, or
  1012. on what machine the task will be executed. You can't even know if the task will
  1013. run in a timely manner.
  1014. The ancient async sayings tells us that “asserting the world is the
  1015. responsibility of the task”. What this means is that the world view may
  1016. have changed since the task was requested, so the task is responsible for
  1017. making sure the world is how it should be; If you have a task
  1018. that re-indexes a search engine, and the search engine should only be
  1019. re-indexed at maximum every 5 minutes, then it must be the tasks
  1020. responsibility to assert that, not the callers.
  1021. Another gotcha is Django model objects. They shouldn't be passed on as
  1022. arguments to tasks. It's almost always better to re-fetch the object from
  1023. the database when the task is running instead, as using old data may lead
  1024. to race conditions.
  1025. Imagine the following scenario where you have an article and a task
  1026. that automatically expands some abbreviations in it:
  1027. .. code-block:: python
  1028. class Article(models.Model):
  1029. title = models.CharField()
  1030. body = models.TextField()
  1031. @app.task
  1032. def expand_abbreviations(article):
  1033. article.body.replace('MyCorp', 'My Corporation')
  1034. article.save()
  1035. First, an author creates an article and saves it, then the author
  1036. clicks on a button that initiates the abbreviation task:
  1037. .. code-block:: pycon
  1038. >>> article = Article.objects.get(id=102)
  1039. >>> expand_abbreviations.delay(article)
  1040. Now, the queue is very busy, so the task won't be run for another 2 minutes.
  1041. In the meantime another author makes changes to the article, so
  1042. when the task is finally run, the body of the article is reverted to the old
  1043. version because the task had the old body in its argument.
  1044. Fixing the race condition is easy, just use the article id instead, and
  1045. re-fetch the article in the task body:
  1046. .. code-block:: python
  1047. @app.task
  1048. def expand_abbreviations(article_id):
  1049. article = Article.objects.get(id=article_id)
  1050. article.body.replace('MyCorp', 'My Corporation')
  1051. article.save()
  1052. .. code-block:: pycon
  1053. >>> expand_abbreviations(article_id)
  1054. There might even be performance benefits to this approach, as sending large
  1055. messages may be expensive.
  1056. .. _task-database-transactions:
  1057. Database transactions
  1058. ---------------------
  1059. Let's have a look at another example:
  1060. .. code-block:: python
  1061. from django.db import transaction
  1062. @transaction.commit_on_success
  1063. def create_article(request):
  1064. article = Article.objects.create()
  1065. expand_abbreviations.delay(article.pk)
  1066. This is a Django view creating an article object in the database,
  1067. then passing the primary key to a task. It uses the `commit_on_success`
  1068. decorator, which will commit the transaction when the view returns, or
  1069. roll back if the view raises an exception.
  1070. There is a race condition if the task starts executing
  1071. before the transaction has been committed; The database object does not exist
  1072. yet!
  1073. The solution is to *always commit transactions before sending tasks
  1074. depending on state from the current transaction*:
  1075. .. code-block:: python
  1076. @transaction.commit_manually
  1077. def create_article(request):
  1078. try:
  1079. article = Article.objects.create()
  1080. except:
  1081. transaction.rollback()
  1082. raise
  1083. else:
  1084. transaction.commit()
  1085. expand_abbreviations.delay(article.pk)
  1086. .. note::
  1087. Django 1.6 (and later) now enables autocommit mode by default,
  1088. and ``commit_on_success``/``commit_manually`` are deprecated.
  1089. This means each SQL query is wrapped and executed in individual
  1090. transactions, making it less likely to experience the
  1091. problem described above.
  1092. However, enabling ``ATOMIC_REQUESTS`` on the database
  1093. connection will bring back the transaction-per-request model and the
  1094. race condition along with it. In this case, the simple solution is
  1095. using the ``@transaction.non_atomic_requests`` decorator to go back
  1096. to autocommit for that view only.
  1097. .. _task-example:
  1098. Example
  1099. =======
  1100. Let's take a real world example: a blog where comments posted need to be
  1101. filtered for spam. When the comment is created, the spam filter runs in the
  1102. background, so the user doesn't have to wait for it to finish.
  1103. I have a Django blog application allowing comments
  1104. on blog posts. I'll describe parts of the models/views and tasks for this
  1105. application.
  1106. ``blog/models.py``
  1107. ------------------
  1108. The comment model looks like this:
  1109. .. code-block:: python
  1110. from django.db import models
  1111. from django.utils.translation import ugettext_lazy as _
  1112. class Comment(models.Model):
  1113. name = models.CharField(_('name'), max_length=64)
  1114. email_address = models.EmailField(_('email address'))
  1115. homepage = models.URLField(_('home page'),
  1116. blank=True, verify_exists=False)
  1117. comment = models.TextField(_('comment'))
  1118. pub_date = models.DateTimeField(_('Published date'),
  1119. editable=False, auto_add_now=True)
  1120. is_spam = models.BooleanField(_('spam?'),
  1121. default=False, editable=False)
  1122. class Meta:
  1123. verbose_name = _('comment')
  1124. verbose_name_plural = _('comments')
  1125. In the view where the comment is posted, I first write the comment
  1126. to the database, then I launch the spam filter task in the background.
  1127. .. _task-example-blog-views:
  1128. ``blog/views.py``
  1129. -----------------
  1130. .. code-block:: python
  1131. from django import forms
  1132. from django.http import HttpResponseRedirect
  1133. from django.template.context import RequestContext
  1134. from django.shortcuts import get_object_or_404, render_to_response
  1135. from blog import tasks
  1136. from blog.models import Comment
  1137. class CommentForm(forms.ModelForm):
  1138. class Meta:
  1139. model = Comment
  1140. def add_comment(request, slug, template_name='comments/create.html'):
  1141. post = get_object_or_404(Entry, slug=slug)
  1142. remote_addr = request.META.get('REMOTE_ADDR')
  1143. if request.method == 'post':
  1144. form = CommentForm(request.POST, request.FILES)
  1145. if form.is_valid():
  1146. comment = form.save()
  1147. # Check spam asynchronously.
  1148. tasks.spam_filter.delay(comment_id=comment.id,
  1149. remote_addr=remote_addr)
  1150. return HttpResponseRedirect(post.get_absolute_url())
  1151. else:
  1152. form = CommentForm()
  1153. context = RequestContext(request, {'form': form})
  1154. return render_to_response(template_name, context_instance=context)
  1155. To filter spam in comments I use `Akismet`_, the service
  1156. used to filter spam in comments posted to the free blog platform
  1157. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  1158. need to pay. You have to sign up to their service to get an API key.
  1159. To make API calls to `Akismet`_ I use the `akismet.py`_ library written by
  1160. `Michael Foord`_.
  1161. .. _task-example-blog-tasks:
  1162. ``blog/tasks.py``
  1163. -----------------
  1164. .. code-block:: python
  1165. from celery import Celery
  1166. from akismet import Akismet
  1167. from django.core.exceptions import ImproperlyConfigured
  1168. from django.contrib.sites.models import Site
  1169. from blog.models import Comment
  1170. app = Celery(broker='amqp://')
  1171. @app.task
  1172. def spam_filter(comment_id, remote_addr=None):
  1173. logger = spam_filter.get_logger()
  1174. logger.info('Running spam filter for comment %s', comment_id)
  1175. comment = Comment.objects.get(pk=comment_id)
  1176. current_domain = Site.objects.get_current().domain
  1177. akismet = Akismet(settings.AKISMET_KEY, 'http://{0}'.format(domain))
  1178. if not akismet.verify_key():
  1179. raise ImproperlyConfigured('Invalid AKISMET_KEY')
  1180. is_spam = akismet.comment_check(user_ip=remote_addr,
  1181. comment_content=comment.comment,
  1182. comment_author=comment.name,
  1183. comment_author_email=comment.email_address)
  1184. if is_spam:
  1185. comment.is_spam = True
  1186. comment.save()
  1187. return is_spam
  1188. .. _`Akismet`: http://akismet.com/faq/
  1189. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
  1190. .. _`Michael Foord`: http://www.voidspace.org.uk/