tasks.rst 51 KB

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