tasks.rst 51 KB

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