tasks.rst 51 KB

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