tasks.rst 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  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. Only applies if the task calls ``self.retry`` or if the task is decorated
  433. with the :ref:`autoretry_for <task-autoretry>` argument.
  434. The maximum number of attempted retries before giving up.
  435. If the number of retries exceeds this value a :exc:`~@MaxRetriesExceededError`
  436. exception will be raised. *NOTE:* You have to call :meth:`~@Task.retry`
  437. manually, as it will not automatically retry on exception..
  438. The default value is 3.
  439. A value of :const:`None` will disable the retry limit and the
  440. task will retry forever until it succeeds.
  441. .. attribute:: Task.throws
  442. Optional tuple of expected error classes that should not be regarded
  443. as an actual error.
  444. Errors in this list will be reported as a failure to the result backend,
  445. but the worker will not log the event as an error, and no traceback will
  446. be included.
  447. Example:
  448. .. code-block:: python
  449. @task(throws=(KeyError, HttpNotFound)):
  450. def get_foo():
  451. something()
  452. Error types:
  453. - Expected errors (in ``Task.throws``)
  454. Logged with severity ``INFO``, traceback excluded.
  455. - Unexpected errors
  456. Logged with severity ``ERROR``, with traceback included.
  457. .. attribute:: Task.default_retry_delay
  458. Default time in seconds before a retry of the task
  459. should be executed. Can be either :class:`int` or :class:`float`.
  460. Default is a 3 minute delay.
  461. .. attribute:: Task.rate_limit
  462. Set the rate limit for this task type which limits the number of tasks
  463. that can be run in a given time frame. Tasks will still complete when
  464. a rate limit is in effect, but it may take some time before it's allowed to
  465. start.
  466. If this is :const:`None` no rate limit is in effect.
  467. If it is an integer or float, it is interpreted as "tasks per second".
  468. The rate limits can be specified in seconds, minutes or hours
  469. by appending `"/s"`, `"/m"` or `"/h"` to the value. Tasks will be evenly
  470. distributed over the specified time frame.
  471. Example: `"100/m"` (hundred tasks a minute). This will enforce a minimum
  472. delay of 600ms between starting two tasks on the same worker instance.
  473. Default is the :setting:`task_default_rate_limit` setting,
  474. which if not specified means rate limiting for tasks is disabled by default.
  475. Note that this is a *per worker instance* rate limit, and not a global
  476. rate limit. To enforce a global rate limit (e.g. for an API with a
  477. maximum number of requests per second), you must restrict to a given
  478. queue.
  479. .. attribute:: Task.time_limit
  480. The hard time limit, in seconds, for this task. If not set then the workers default
  481. will be used.
  482. .. attribute:: Task.soft_time_limit
  483. The soft time limit for this task. If not set then the workers default
  484. will be used.
  485. .. attribute:: Task.ignore_result
  486. Don't store task state. Note that this means you can't use
  487. :class:`~celery.result.AsyncResult` to check if the task is ready,
  488. or get its return value.
  489. .. attribute:: Task.store_errors_even_if_ignored
  490. If :const:`True`, errors will be stored even if the task is configured
  491. to ignore results.
  492. .. attribute:: Task.serializer
  493. A string identifying the default serialization
  494. method to use. Defaults to the :setting:`task_serializer`
  495. setting. Can be `pickle`, `json`, `yaml`, or any custom
  496. serialization methods that have been registered with
  497. :mod:`kombu.serialization.registry`.
  498. Please see :ref:`calling-serializers` for more information.
  499. .. attribute:: Task.compression
  500. A string identifying the default compression scheme to use.
  501. Defaults to the :setting:`task_compression` setting.
  502. Can be `gzip`, or `bzip2`, or any custom compression schemes
  503. that have been registered with the :mod:`kombu.compression` registry.
  504. Please see :ref:`calling-compression` for more information.
  505. .. attribute:: Task.backend
  506. The result store backend to use for this task. An instance of one of the
  507. backend classes in `celery.backends`. Defaults to `app.backend` which is
  508. defined by the :setting:`result_backend` setting.
  509. .. attribute:: Task.acks_late
  510. If set to :const:`True` messages for this task will be acknowledged
  511. **after** the task has been executed, not *just before*, which is
  512. the default behavior.
  513. Note that this means the task may be executed twice if the worker
  514. crashes in the middle of execution, which may be acceptable for some
  515. applications.
  516. The global default can be overridden by the :setting:`task_acks_late`
  517. setting.
  518. .. _task-track-started:
  519. .. attribute:: Task.track_started
  520. If :const:`True` the task will report its status as "started"
  521. when the task is executed by a worker.
  522. The default value is :const:`False` as the normal behavior is to not
  523. report that level of granularity. Tasks are either pending, finished,
  524. or waiting to be retried. Having a "started" status can be useful for
  525. when there are long running tasks and there is a need to report which
  526. task is currently running.
  527. The host name and process id of the worker executing the task
  528. will be available in the state meta-data (e.g. `result.info['pid']`)
  529. The global default can be overridden by the
  530. :setting:`task_track_started` setting.
  531. .. seealso::
  532. The API reference for :class:`~@Task`.
  533. .. _task-states:
  534. States
  535. ======
  536. Celery can keep track of the tasks current state. The state also contains the
  537. result of a successful task, or the exception and traceback information of a
  538. failed task.
  539. There are several *result backends* to choose from, and they all have
  540. different strengths and weaknesses (see :ref:`task-result-backends`).
  541. During its lifetime a task will transition through several possible states,
  542. and each state may have arbitrary meta-data attached to it. When a task
  543. moves into a new state the previous state is
  544. forgotten about, but some transitions can be deducted, (e.g. a task now
  545. in the :state:`FAILED` state, is implied to have been in the
  546. :state:`STARTED` state at some point).
  547. There are also sets of states, like the set of
  548. :state:`FAILURE_STATES`, and the set of :state:`READY_STATES`.
  549. The client uses the membership of these sets to decide whether
  550. the exception should be re-raised (:state:`PROPAGATE_STATES`), or whether
  551. the state can be cached (it can if the task is ready).
  552. You can also define :ref:`custom-states`.
  553. .. _task-result-backends:
  554. Result Backends
  555. ---------------
  556. If you want to keep track of tasks or need the return values, then Celery
  557. must store or send the states somewhere so that they can be retrieved later.
  558. There are several built-in result backends to choose from: SQLAlchemy/Django ORM,
  559. Memcached, RabbitMQ/QPid (``rpc``), and Redis -- or you can define your own.
  560. No backend works well for every use case.
  561. You should read about the strengths and weaknesses of each backend, and choose
  562. the most appropriate for your needs.
  563. .. seealso::
  564. :ref:`conf-result-backend`
  565. RPC Result Backend (RabbitMQ/QPid)
  566. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  567. The RPC result backend (`rpc://`) is special as it does not actually *store*
  568. the states, but rather sends them as messages. This is an important difference as it
  569. means that a result *can only be retrieved once*, and *only by the client
  570. that initiated the task*. Two different processes can not wait for the same result.
  571. Even with that limitation, it is an excellent choice if you need to receive
  572. state changes in real-time. Using messaging means the client does not have to
  573. poll for new states.
  574. The messages are transient (non-persistent) by default, so the results will
  575. disappear if the broker restarts. You can configure the result backend to send
  576. persistent messages using the :setting:`result_persistent` setting.
  577. Database Result Backend
  578. ~~~~~~~~~~~~~~~~~~~~~~~
  579. Keeping state in the database can be convenient for many, especially for
  580. web applications with a database already in place, but it also comes with
  581. limitations.
  582. * Polling the database for new states is expensive, and so you should
  583. increase the polling intervals of operations such as `result.get()`.
  584. * Some databases use a default transaction isolation level that
  585. is not suitable for polling tables for changes.
  586. In MySQL the default transaction isolation level is `REPEATABLE-READ`, which
  587. means the transaction will not see changes by other transactions until the
  588. transaction is committed. It is recommended that you change to the
  589. `READ-COMMITTED` isolation level.
  590. .. _task-builtin-states:
  591. Built-in States
  592. ---------------
  593. .. state:: PENDING
  594. PENDING
  595. ~~~~~~~
  596. Task is waiting for execution or unknown.
  597. Any task id that is not known is implied to be in the pending state.
  598. .. state:: STARTED
  599. STARTED
  600. ~~~~~~~
  601. Task has been started.
  602. Not reported by default, to enable please see :attr:`@Task.track_started`.
  603. :meta-data: `pid` and `hostname` of the worker process executing
  604. the task.
  605. .. state:: SUCCESS
  606. SUCCESS
  607. ~~~~~~~
  608. Task has been successfully executed.
  609. :meta-data: `result` contains the return value of the task.
  610. :propagates: Yes
  611. :ready: Yes
  612. .. state:: FAILURE
  613. FAILURE
  614. ~~~~~~~
  615. Task execution resulted in failure.
  616. :meta-data: `result` contains the exception occurred, and `traceback`
  617. contains the backtrace of the stack at the point when the
  618. exception was raised.
  619. :propagates: Yes
  620. .. state:: RETRY
  621. RETRY
  622. ~~~~~
  623. Task is being retried.
  624. :meta-data: `result` contains the exception that caused the retry,
  625. and `traceback` contains the backtrace of the stack at the point
  626. when the exceptions was raised.
  627. :propagates: No
  628. .. state:: REVOKED
  629. REVOKED
  630. ~~~~~~~
  631. Task has been revoked.
  632. :propagates: Yes
  633. .. _custom-states:
  634. Custom states
  635. -------------
  636. You can easily define your own states, all you need is a unique name.
  637. The name of the state is usually an uppercase string. As an example
  638. you could have a look at :mod:`abortable tasks <~celery.contrib.abortable>`
  639. which defines its own custom :state:`ABORTED` state.
  640. Use :meth:`~@Task.update_state` to update a task's state:.
  641. .. code-block:: python
  642. @app.task(bind=True)
  643. def upload_files(self, filenames):
  644. for i, file in enumerate(filenames):
  645. if not self.request.called_directly:
  646. self.update_state(state='PROGRESS',
  647. meta={'current': i, 'total': len(filenames)})
  648. Here I created the state `"PROGRESS"`, which tells any application
  649. aware of this state that the task is currently in progress, and also where
  650. it is in the process by having `current` and `total` counts as part of the
  651. state meta-data. This can then be used to create e.g. progress bars.
  652. .. _pickling_exceptions:
  653. Creating pickleable exceptions
  654. ------------------------------
  655. A rarely known Python fact is that exceptions must conform to some
  656. simple rules to support being serialized by the pickle module.
  657. Tasks that raise exceptions that are not pickleable will not work
  658. properly when Pickle is used as the serializer.
  659. To make sure that your exceptions are pickleable the exception
  660. *MUST* provide the original arguments it was instantiated
  661. with in its ``.args`` attribute. The simplest way
  662. to ensure this is to have the exception call ``Exception.__init__``.
  663. Let's look at some examples that work, and one that doesn't:
  664. .. code-block:: python
  665. # OK:
  666. class HttpError(Exception):
  667. pass
  668. # BAD:
  669. class HttpError(Exception):
  670. def __init__(self, status_code):
  671. self.status_code = status_code
  672. # OK:
  673. class HttpError(Exception):
  674. def __init__(self, status_code):
  675. self.status_code = status_code
  676. Exception.__init__(self, status_code) # <-- REQUIRED
  677. So the rule is:
  678. For any exception that supports custom arguments ``*args``,
  679. ``Exception.__init__(self, *args)`` must be used.
  680. There is no special support for *keyword arguments*, so if you
  681. want to preserve keyword arguments when the exception is unpickled
  682. you have to pass them as regular args:
  683. .. code-block:: python
  684. class HttpError(Exception):
  685. def __init__(self, status_code, headers=None, body=None):
  686. self.status_code = status_code
  687. self.headers = headers
  688. self.body = body
  689. super(HttpError, self).__init__(status_code, headers, body)
  690. .. _task-semipredicates:
  691. Semipredicates
  692. ==============
  693. The worker wraps the task in a tracing function which records the final
  694. state of the task. There are a number of exceptions that can be used to
  695. signal this function to change how it treats the return of the task.
  696. .. _task-semipred-ignore:
  697. Ignore
  698. ------
  699. The task may raise :exc:`~@Ignore` to force the worker to ignore the
  700. task. This means that no state will be recorded for the task, but the
  701. message is still acknowledged (removed from queue).
  702. This can be used if you want to implement custom revoke-like
  703. functionality, or manually store the result of a task.
  704. Example keeping revoked tasks in a Redis set:
  705. .. code-block:: python
  706. from celery.exceptions import Ignore
  707. @app.task(bind=True)
  708. def some_task(self):
  709. if redis.ismember('tasks.revoked', self.request.id):
  710. raise Ignore()
  711. Example that stores results manually:
  712. .. code-block:: python
  713. from celery import states
  714. from celery.exceptions import Ignore
  715. @app.task(bind=True)
  716. def get_tweets(self, user):
  717. timeline = twitter.get_timeline(user)
  718. if not self.request.called_directly:
  719. self.update_state(state=states.SUCCESS, meta=timeline)
  720. raise Ignore()
  721. .. _task-semipred-reject:
  722. Reject
  723. ------
  724. The task may raise :exc:`~@Reject` to reject the task message using
  725. AMQPs ``basic_reject`` method. This will not have any effect unless
  726. :attr:`Task.acks_late` is enabled.
  727. Rejecting a message has the same effect as acking it, but some
  728. brokers may implement additional functionality that can be used.
  729. For example RabbitMQ supports the concept of `Dead Letter Exchanges`_
  730. where a queue can be configured to use a dead letter exchange that rejected
  731. messages are redelivered to.
  732. .. _`Dead Letter Exchanges`: http://www.rabbitmq.com/dlx.html
  733. Reject can also be used to re-queue messages, but please be very careful
  734. when using this as it can easily result in an infinite message loop.
  735. Example using reject when a task causes an out of memory condition:
  736. .. code-block:: python
  737. import errno
  738. from celery.exceptions import Reject
  739. @app.task(bind=True, acks_late=True)
  740. def render_scene(self, path):
  741. file = get_file(path)
  742. try:
  743. renderer.render_scene(file)
  744. # if the file is too big to fit in memory
  745. # we reject it so that it's redelivered to the dead letter exchange
  746. # and we can manually inspect the situation.
  747. except MemoryError as exc:
  748. raise Reject(exc, requeue=False)
  749. except OSError as exc:
  750. if exc.errno == errno.ENOMEM:
  751. raise Reject(exc, requeue=False)
  752. # For any other error we retry after 10 seconds.
  753. except Exception as exc:
  754. raise self.retry(exc, countdown=10)
  755. Example re-queuing the message:
  756. .. code-block:: python
  757. from celery.exceptions import Reject
  758. @app.task(bind=True, acks_late=True)
  759. def requeues(self):
  760. if not self.request.delivery_info['redelivered']:
  761. raise Reject('no reason', requeue=True)
  762. print('received two times')
  763. Consult your broker documentation for more details about the ``basic_reject``
  764. method.
  765. .. _task-semipred-retry:
  766. Retry
  767. -----
  768. The :exc:`~@Retry` exception is raised by the ``Task.retry`` method
  769. to tell the worker that the task is being retried.
  770. .. _task-custom-classes:
  771. Custom task classes
  772. ===================
  773. All tasks inherit from the :class:`@Task` class.
  774. The :meth:`~@Task.run` method becomes the task body.
  775. As an example, the following code,
  776. .. code-block:: python
  777. @app.task
  778. def add(x, y):
  779. return x + y
  780. will do roughly this behind the scenes:
  781. .. code-block:: python
  782. class _AddTask(app.Task):
  783. def run(self, x, y):
  784. return x + y
  785. add = app.tasks[_AddTask.name]
  786. Instantiation
  787. -------------
  788. A task is **not** instantiated for every request, but is registered
  789. in the task registry as a global instance.
  790. This means that the ``__init__`` constructor will only be called
  791. once per process, and that the task class is semantically closer to an
  792. Actor.
  793. If you have a task,
  794. .. code-block:: python
  795. from celery import Task
  796. class NaiveAuthenticateServer(Task):
  797. def __init__(self):
  798. self.users = {'george': 'password'}
  799. def run(self, username, password):
  800. try:
  801. return self.users[username] == password
  802. except KeyError:
  803. return False
  804. And you route every request to the same process, then it
  805. will keep state between requests.
  806. This can also be useful to cache resources,
  807. e.g. a base Task class that caches a database connection:
  808. .. code-block:: python
  809. from celery import Task
  810. class DatabaseTask(Task):
  811. _db = None
  812. @property
  813. def db(self):
  814. if self._db is None:
  815. self._db = Database.connect()
  816. return self._db
  817. that can be added to tasks like this:
  818. .. code-block:: python
  819. @app.task(base=DatabaseTask)
  820. def process_rows():
  821. for row in process_rows.db.table.all():
  822. process_row(row)
  823. The ``db`` attribute of the ``process_rows`` task will then
  824. always stay the same in each process.
  825. Handlers
  826. --------
  827. .. method:: after_return(self, status, retval, task_id, args, kwargs, einfo)
  828. Handler called after the task returns.
  829. :param status: Current task state.
  830. :param retval: Task return value/exception.
  831. :param task_id: Unique id of the task.
  832. :param args: Original arguments for the task that returned.
  833. :param kwargs: Original keyword arguments for the task
  834. that returned.
  835. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  836. instance, containing the traceback (if any).
  837. The return value of this handler is ignored.
  838. .. method:: on_failure(self, exc, task_id, args, kwargs, einfo)
  839. This is run by the worker when the task fails.
  840. :param exc: The exception raised by the task.
  841. :param task_id: Unique id of the failed task.
  842. :param args: Original arguments for the task that failed.
  843. :param kwargs: Original keyword arguments for the task
  844. that failed.
  845. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  846. instance, containing the traceback.
  847. The return value of this handler is ignored.
  848. .. method:: on_retry(self, exc, task_id, args, kwargs, einfo)
  849. This is run by the worker when the task is to be retried.
  850. :param exc: The exception sent to :meth:`~@Task.retry`.
  851. :param task_id: Unique id of the retried task.
  852. :param args: Original arguments for the retried task.
  853. :param kwargs: Original keyword arguments for the retried task.
  854. :keyword einfo: :class:`~billiard.einfo.ExceptionInfo`
  855. instance, containing the traceback.
  856. The return value of this handler is ignored.
  857. .. method:: on_success(self, retval, task_id, args, kwargs)
  858. Run by the worker if the task executes successfully.
  859. :param retval: The return value of the task.
  860. :param task_id: Unique id of the executed task.
  861. :param args: Original arguments for the executed task.
  862. :param kwargs: Original keyword arguments for the executed task.
  863. The return value of this handler is ignored.
  864. .. _task-how-they-work:
  865. How it works
  866. ============
  867. Here come the technical details. This part isn't something you need to know,
  868. but you may be interested.
  869. All defined tasks are listed in a registry. The registry contains
  870. a list of task names and their task classes. You can investigate this registry
  871. yourself:
  872. .. code-block:: pycon
  873. >>> from proj.celery import app
  874. >>> app.tasks
  875. {'celery.chord_unlock':
  876. <@task: celery.chord_unlock>,
  877. 'celery.backend_cleanup':
  878. <@task: celery.backend_cleanup>,
  879. 'celery.chord':
  880. <@task: celery.chord>}
  881. This is the list of tasks built-in to celery. Note that tasks
  882. will only be registered when the module they are defined in is imported.
  883. The default loader imports any modules listed in the
  884. :setting:`imports` setting.
  885. The :meth:`@task` decorator is responsible for registering your task
  886. in the applications task registry.
  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 blog 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/