tasks.rst 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. .. _guide-tasks:
  2. =======
  3. Tasks
  4. =======
  5. .. contents::
  6. :local:
  7. .. _task-basics:
  8. Basics
  9. ======
  10. A task is a class that encapsulates a function and its execution options.
  11. Given a function ``create_user``, that takes two arguments: ``username`` and
  12. ``password``, you can create a task like this:
  13. .. code-block:: python
  14. from celery.task import Task
  15. from django.contrib.auth import User
  16. class CreateUserTask(Task):
  17. def run(self, username, password):
  18. User.objects.create(username=username, password=password)
  19. For convenience there is a shortcut decorator that turns any function into
  20. a task:
  21. .. code-block:: python
  22. from celery.decorators import task
  23. from django.contrib.auth import User
  24. @task
  25. def create_user(username, password):
  26. User.objects.create(username=username, password=password)
  27. The task decorator takes the same execution options as the
  28. :class:`~celery.task.base.Task` class does:
  29. .. code-block:: python
  30. @task(serializer="json")
  31. def create_user(username, password):
  32. User.objects.create(username=username, password=password)
  33. .. _task-keyword-arguments:
  34. Default keyword arguments
  35. =========================
  36. Celery supports a set of default arguments that can be forwarded to any task.
  37. Tasks can choose not to take these, or list the ones they want.
  38. The worker will do the right thing.
  39. The current default keyword arguments are:
  40. :task_id: The unique id of the executing task.
  41. :task_name: Name of the currently executing task.
  42. :task_retries: How many times the current task has been retried.
  43. An integer starting at ``0``.
  44. :task_is_eager: Set to :const:`True` if the task is executed locally in
  45. the client, kand not by a worker.
  46. :logfile: The log file, can be passed on to
  47. :meth:`~celery.task.base.Task.get_logger` to gain access to
  48. the workers log file. See `Logging`_.
  49. :loglevel: The current loglevel used.
  50. :delivery_info: Additional message delivery information. This is a mapping
  51. containing the exchange and routing key used to deliver this
  52. task. It's used by e.g. :meth:`~celery.task.base.Task.retry`
  53. to resend the task to the same destination queue.
  54. **NOTE** As some messaging backends doesn't have advanced routing
  55. capabilities, you can't trust the availability of keys in this mapping.
  56. .. _task-logging:
  57. Logging
  58. =======
  59. You can use the workers logger to add diagnostic output to
  60. the worker log:
  61. .. code-block:: python
  62. class AddTask(Task):
  63. def run(self, x, y, **kwargs):
  64. logger = self.get_logger(**kwargs)
  65. logger.info("Adding %s + %s" % (x, y))
  66. return x + y
  67. or using the decorator syntax:
  68. .. code-block:: python
  69. @task()
  70. def add(x, y, **kwargs):
  71. logger = add.get_logger(**kwargs)
  72. logger.info("Adding %s + %s" % (x, y))
  73. return x + y
  74. There are several logging levels available, and the workers ``loglevel``
  75. setting decides whether or not they will be written to the log file.
  76. Of course, you can also simply use ``print`` as anything written to standard
  77. out/-err will be written to the logfile as well.
  78. .. _task-retry:
  79. Retrying a task if something fails
  80. ==================================
  81. Simply use :meth:`~celery.task.base.Task.retry` to re-send the task.
  82. It will do the right thing, and respect the
  83. :attr:`~celery.task.base.Task.max_retries` attribute:
  84. .. code-block:: python
  85. @task()
  86. def send_twitter_status(oauth, tweet, **kwargs):
  87. try:
  88. twitter = Twitter(oauth)
  89. twitter.update_status(tweet)
  90. except (Twitter.FailWhaleError, Twitter.LoginError), exc:
  91. send_twitter_status.retry(args=[oauth, tweet], kwargs=kwargs, exc=exc)
  92. Here we used the ``exc`` argument to pass the current exception to
  93. :meth:`~celery.task.base.Task.retry`. At each step of the retry this exception
  94. is available as the tombstone (result) of the task. When
  95. :attr:`~celery.task.base.Task.max_retries` has been exceeded this is the
  96. exception raised. However, if an ``exc`` argument is not provided the
  97. :exc:`~celery.exceptions.RetryTaskError` exception is raised instead.
  98. **Important note:** The task has to take the magic keyword arguments
  99. in order for max retries to work properly, this is because it keeps track
  100. of the current number of retries using the ``task_retries`` keyword argument
  101. passed on to the task. In addition, it also uses the ``task_id`` keyword
  102. argument to use the same task id, and ``delivery_info`` to route the
  103. retried task to the same destination.
  104. .. _task-retry-custom-delay:
  105. Using a custom retry delay
  106. --------------------------
  107. When a task is to be retried, it will wait for a given amount of time
  108. before doing so. The default delay is in the
  109. :attr:`~celery.task.base.Task.default_retry_delay`
  110. attribute on the task. By default this is set to 3 minutes. Note that the
  111. unit for setting the delay is in seconds (int or float).
  112. You can also provide the ``countdown`` argument to
  113. :meth:`~celery.task.base.Task.retry` to override this default.
  114. .. code-block:: python
  115. class MyTask(Task):
  116. default_retry_delay = 30 * 60 # retry in 30 minutes
  117. def run(self, x, y, **kwargs):
  118. try:
  119. ...
  120. except Exception, exc:
  121. self.retry([x, y], kwargs, exc=exc,
  122. countdown=60) # override the default and
  123. # - retry in 1 minute
  124. .. _task-options:
  125. Task options
  126. ============
  127. General
  128. -------
  129. .. _task-general-options:
  130. .. attribute:: Task.name
  131. The name the task is registered as.
  132. You can set this name manually, or just use the default which is
  133. automatically generated using the module and class name.
  134. .. attribute:: Task.abstract
  135. Abstract classes are not registered, but are used as the
  136. superclass when making new task types by subclassing.
  137. .. attribute:: Task.max_retries
  138. The maximum number of attempted retries before giving up.
  139. If this exceeds the :exc:`~celery.exceptions.MaxRetriesExceeded`
  140. an exception will be raised. *NOTE:* You have to :meth:`retry`
  141. manually, it's not something that happens automatically.
  142. .. attribute:: Task.default_retry_delay
  143. Default time in seconds before a retry of the task
  144. should be executed. Can be either an ``int`` or a ``float``.
  145. Default is a 3 minute delay.
  146. .. attribute:: Task.rate_limit
  147. Set the rate limit for this task type, i.e. how many times in
  148. a given period of time is the task allowed to run.
  149. If this is :const:`None` no rate limit is in effect.
  150. If it is an integer, it is interpreted as "tasks per second".
  151. The rate limits can be specified in seconds, minutes or hours
  152. by appending ``"/s"``, ``"/m"`` or ``"/h"`` to the value.
  153. Example: ``"100/m"`` (hundred tasks a minute). Default is the
  154. :setting:`CELERY_DEFAULT_RATE_LIMIT` setting, which if not specified means
  155. rate limiting for tasks is turned off by default.
  156. .. attribute:: Task.ignore_result
  157. Don't store task state. This means you can't use the
  158. :class:`~celery.result.AsyncResult` to check if the task is ready,
  159. or get its return value.
  160. .. attribute:: Task.store_errors_even_if_ignored
  161. If true, errors will be stored even if the task is configured
  162. to ignore results.
  163. .. attribute:: Task.send_error_emails
  164. Send an e-mail whenever a task of this type fails.
  165. Defaults to the :setting:`CELERY_SEND_TASK_ERROR_EMAILS` setting.
  166. See :ref:`conf-error-mails` for more information.
  167. .. attribute:: Task.error_whitelist
  168. If the sending of error e-emails is enabled for this task, then
  169. this is a whitelist of exceptions to actually send e-mails about.
  170. .. attribute:: Task.serializer
  171. A string identifying the default serialization
  172. method to use. Defaults to the :setting:`CELERY_TASK_SERIALIZER`
  173. setting. Can be ``pickle`` ``json``, ``yaml``, or any custom
  174. serialization methods that have been registered with
  175. :mod:`carrot.serialization.registry`.
  176. Please see :ref:`executing-serializers` for more information.
  177. .. attribute:: Task.backend
  178. The result store backend to use for this task. Defaults to the
  179. :setting:`CELERY_RESULT_BACKEND` setting.
  180. .. attribute:: Task.acks_late
  181. If set to :const:`True` messages for this task will be acknowledged
  182. **after** the task has been executed, not *just before*, which is
  183. the default behavior.
  184. Note that this means the task may be executed twice if the worker
  185. crashes in the middle of execution, which may be acceptable for some
  186. applications.
  187. The global default can be overriden by the :setting:`CELERY_ACKS_LATE`
  188. setting.
  189. .. attribute:: Task.track_started
  190. If :const:`True` the task will report its status as "started"
  191. when the task is executed by a worker.
  192. The default value is ``False`` as the normal behaviour is to not
  193. report that level of granularity. Tasks are either pending, finished,
  194. or waiting to be retried. Having a "started" status can be useful for
  195. when there are long running tasks and there is a need to report which
  196. task is currently running.
  197. The global default can be overridden by the
  198. :setting:`CELERY_TRACK_STARTED` setting.
  199. .. seealso::
  200. The API reference for :class:`~celery.task.base.Task`.
  201. .. _task-message-options:
  202. Message and routing options
  203. ---------------------------
  204. .. attribute:: Task.queue
  205. Use the routing settings from a queue defined in :setting:`CELERY_QUEUES`.
  206. If defined the :attr:`exchange` and :attr:`routing_key` options will be
  207. ignored.
  208. .. attribute:: Task.exchange
  209. Override the global default ``exchange`` for this task.
  210. .. attribute:: Task.routing_key
  211. Override the global default ``routing_key`` for this task.
  212. .. attribute:: Task.mandatory
  213. If set, the task message has mandatory routing. By default the task
  214. is silently dropped by the broker if it can't be routed to a queue.
  215. However -- If the task is mandatory, an exception will be raised
  216. instead.
  217. .. attribute:: Task.immediate
  218. Request immediate delivery. If the task cannot be routed to a
  219. task worker immediately, an exception will be raised. This is
  220. instead of the default behavior, where the broker will accept and
  221. queue the task, but with no guarantee that the task will ever
  222. be executed.
  223. .. attribute:: Task.priority
  224. The message priority. A number from 0 to 9, where 0 is the
  225. highest priority. **Note:** At the time writing this, RabbitMQ did not yet support
  226. priorities
  227. .. seealso::
  228. :ref:`executing-routing` for more information about message options,
  229. and :ref:`guide-routing`.
  230. .. _task-example:
  231. Example
  232. =======
  233. Let's take a real wold example; A blog where comments posted needs to be
  234. filtered for spam. When the comment is created, the spam filter runs in the
  235. background, so the user doesn't have to wait for it to finish.
  236. We have a Django blog application allowing comments
  237. on blog posts. We'll describe parts of the models/views and tasks for this
  238. application.
  239. blog/models.py
  240. --------------
  241. The comment model looks like this:
  242. .. code-block:: python
  243. from django.db import models
  244. from django.utils.translation import ugettext_lazy as _
  245. class Comment(models.Model):
  246. name = models.CharField(_("name"), max_length=64)
  247. email_address = models.EmailField(_("e-mail address"))
  248. homepage = models.URLField(_("home page"),
  249. blank=True, verify_exists=False)
  250. comment = models.TextField(_("comment"))
  251. pub_date = models.DateTimeField(_("Published date"),
  252. editable=False, auto_add_now=True)
  253. is_spam = models.BooleanField(_("spam?"),
  254. default=False, editable=False)
  255. class Meta:
  256. verbose_name = _("comment")
  257. verbose_name_plural = _("comments")
  258. In the view where the comment is posted, we first write the comment
  259. to the database, then we launch the spam filter task in the background.
  260. .. _task-example-blog-views:
  261. blog/views.py
  262. -------------
  263. .. code-block:: python
  264. from django import forms
  265. from django.http import HttpResponseRedirect
  266. from django.template.context import RequestContext
  267. from django.shortcuts import get_object_or_404, render_to_response
  268. from blog import tasks
  269. from blog.models import Comment
  270. class CommentForm(forms.ModelForm):
  271. class Meta:
  272. model = Comment
  273. def add_comment(request, slug, template_name="comments/create.html"):
  274. post = get_object_or_404(Entry, slug=slug)
  275. remote_addr = request.META.get("REMOTE_ADDR")
  276. if request.method == "post":
  277. form = CommentForm(request.POST, request.FILES)
  278. if form.is_valid():
  279. comment = form.save()
  280. # Check spam asynchronously.
  281. tasks.spam_filter.delay(comment_id=comment.id,
  282. remote_addr=remote_addr)
  283. return HttpResponseRedirect(post.get_absolute_url())
  284. else:
  285. form = CommentForm()
  286. context = RequestContext(request, {"form": form})
  287. return render_to_response(template_name, context_instance=context)
  288. To filter spam in comments we use `Akismet`_, the service
  289. used to filter spam in comments posted to the free weblog platform
  290. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  291. need to pay. You have to sign up to their service to get an API key.
  292. To make API calls to `Akismet`_ we use the `akismet.py`_ library written by
  293. Michael Foord.
  294. .. _task-example-blog-tasks:
  295. blog/tasks.py
  296. -------------
  297. .. code-block:: python
  298. from akismet import Akismet
  299. from celery.decorators import task
  300. from django.core.exceptions import ImproperlyConfigured
  301. from django.contrib.sites.models import Site
  302. from blog.models import Comment
  303. @task
  304. def spam_filter(comment_id, remote_addr=None, **kwargs):
  305. logger = spam_filter.get_logger(**kwargs)
  306. logger.info("Running spam filter for comment %s" % comment_id)
  307. comment = Comment.objects.get(pk=comment_id)
  308. current_domain = Site.objects.get_current().domain
  309. akismet = Akismet(settings.AKISMET_KEY, "http://%s" % domain)
  310. if not akismet.verify_key():
  311. raise ImproperlyConfigured("Invalid AKISMET_KEY")
  312. is_spam = akismet.comment_check(user_ip=remote_addr,
  313. comment_content=comment.comment,
  314. comment_author=comment.name,
  315. comment_author_email=comment.email_address)
  316. if is_spam:
  317. comment.is_spam = True
  318. comment.save()
  319. return is_spam
  320. .. _`Akismet`: http://akismet.com/faq/
  321. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
  322. .. _task-how-they-work:
  323. How it works
  324. ============
  325. Here comes the technical details, this part isn't something you need to know,
  326. but you may be interested.
  327. All defined tasks are listed in a registry. The registry contains
  328. a list of task names and their task classes. You can investigate this registry
  329. yourself:
  330. .. code-block:: python
  331. >>> from celery import registry
  332. >>> from celery import task
  333. >>> registry.tasks
  334. {'celery.delete_expired_task_meta':
  335. <PeriodicTask: celery.delete_expired_task_meta (periodic)>,
  336. 'celery.task.http.HttpDispatchTask':
  337. <Task: celery.task.http.HttpDispatchTask (regular)>,
  338. 'celery.execute_remote':
  339. <Task: celery.execute_remote (regular)>,
  340. 'celery.map_async':
  341. <Task: celery.map_async (regular)>,
  342. 'celery.ping':
  343. <Task: celery.ping (regular)>}
  344. This is the list of tasks built-in to celery. Note that we had to import
  345. ``celery.task`` first for these to show up. This is because the tasks will
  346. only be registered when the module they are defined in is imported.
  347. The default loader imports any modules listed in the
  348. :setting:`CELERY_IMPORTS` setting.
  349. The entity responsible for registering your task in the registry is a
  350. meta class, :class:`~celery.task.base.TaskType`. This is the default
  351. meta class for :class:`~celery.task.base.Task`. If you want to register
  352. your task manually you can set the :attr:`~celery.task.base.Task.abstract`
  353. attribute:
  354. .. code-block:: python
  355. class MyTask(Task):
  356. abstract = True
  357. This way the task won't be registered, but any task subclassing it will.
  358. When tasks are sent, we don't send the function code, just the name
  359. of the task. When the worker receives the message it can just look it up in
  360. the task registry to find the execution code.
  361. This means that your workers should always be updated with the same software
  362. as the client. This is a drawback, but the alternative is a technical
  363. challenge that has yet to be solved.
  364. .. _task-best-practices:
  365. Tips and Best Practices
  366. =======================
  367. .. _task-ignore_results:
  368. Ignore results you don't want
  369. -----------------------------
  370. If you don't care about the results of a task, be sure to set the
  371. :attr:`~celery.task.base.Task.ignore_result` option, as storing results
  372. wastes time and resources.
  373. .. code-block:: python
  374. @task(ignore_result=True)
  375. def mytask(...)
  376. something()
  377. Results can even be disabled globally using the
  378. :setting:`CELERY_IGNORE_RESULT` setting.
  379. .. _task-disable-rate-limits:
  380. Disable rate limits if they're not used
  381. ---------------------------------------
  382. Disabling rate limits altogether is recommended if you don't have
  383. any tasks using them. This is because the rate limit subsystem introduces
  384. quite a lot of complexity.
  385. Set the :setting:`CELERY_DISABLE_RATE_LIMITS` setting to globally disable
  386. rate limits:
  387. .. code-block:: python
  388. CELERY_DISABLE_RATE_LIMITS = True
  389. .. _task-synchronous-subtasks:
  390. Avoid launching synchronous subtasks
  391. ------------------------------------
  392. Having a task wait for the result of another task is really inefficient,
  393. and may even cause a deadlock if the worker pool is exhausted.
  394. Make your design asynchronous instead, for example by using *callbacks*.
  395. Bad:
  396. .. code-block:: python
  397. @task()
  398. def update_page_info(url):
  399. page = fetch_page.delay(url).get()
  400. info = parse_page.delay(url, page).get()
  401. store_page_info.delay(url, info)
  402. @task()
  403. def fetch_page(url):
  404. return myhttplib.get(url)
  405. @task()
  406. def parse_page(url, page):
  407. return myparser.parse_document(page)
  408. @task()
  409. def store_page_info(url, info):
  410. return PageInfo.objects.create(url, info)
  411. Good:
  412. .. code-block:: python
  413. @task(ignore_result=True)
  414. def update_page_info(url):
  415. # fetch_page -> parse_page -> store_page
  416. fetch_page.delay(url, callback=subtask(parse_page,
  417. callback=subtask(store_page_info)))
  418. @task(ignore_result=True)
  419. def fetch_page(url, callback=None):
  420. page = myhttplib.get(url)
  421. if callback:
  422. # The callback may have been serialized with JSON,
  423. # so best practice is to convert the subtask dict back
  424. # into a subtask object.
  425. subtask(callback).delay(url, page)
  426. @task(ignore_result=True)
  427. def parse_page(url, page, callback=None):
  428. info = myparser.parse_document(page)
  429. if callback:
  430. subtask(callback).delay(url, info)
  431. @task(ignore_result=True)
  432. def store_page_info(url, info):
  433. PageInfo.objects.create(url, info)
  434. We use :class:`~celery.task.sets.subtask` here to safely pass
  435. around the callback task. :class:`~celery.task.sets.subtask` is a
  436. subclass of dict used to wrap the arguments and execution options
  437. for a single task invocation.
  438. .. seealso::
  439. :ref:`sets-subtasks` for more information about subtasks.
  440. .. _task-performance-and-strategies:
  441. Performance and Strategies
  442. ==========================
  443. .. _task-granularity:
  444. Granularity
  445. -----------
  446. The task granularity is the amount of computation needed by each subtask.
  447. It's generally better to split your problem up in many small tasks, than
  448. having a few long running ones.
  449. With smaller tasks you can process more tasks in parallel and the tasks
  450. won't run long enough to block the worker from processing other waiting tasks.
  451. However, executing a task does have overhead. A message needs to be sent, data
  452. may not be local, etc. So if the tasks are too fine-grained the additional
  453. overhead may not be worth it in the end.
  454. .. seealso::
  455. The book `Art of Concurrency`_ has a whole section dedicated to the topic
  456. of task granularity.
  457. .. _`Art of Concurrency`: http://oreilly.com/catalog/9780596521547
  458. .. _task-data-locality:
  459. Data locality
  460. -------------
  461. The worker processing the task should be as close to the data as
  462. possible. The best would be to have a copy in memory, the worst being a
  463. full transfer from another continent.
  464. If the data is far away, you could try to run another worker at location, or
  465. if that's not possible, cache often used data, or preload data you know
  466. is going to be used.
  467. The easiest way to share data between workers is to use a distributed caching
  468. system, like `memcached`_.
  469. .. seealso::
  470. The paper `Distributed Computing Economics`_ by Jim Gray is an excellent
  471. introduction to the topic of data locality.
  472. .. _`Distributed Computing Economics`:
  473. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  474. .. _`memcached`: http://memcached.org/
  475. .. _task-state:
  476. State
  477. -----
  478. Since celery is a distributed system, you can't know in which process, or even
  479. on what machine the task will run. Indeed you can't even know if the task will
  480. run in a timely manner, so please be wary of the state you pass on to tasks.
  481. One gotcha is Django model objects. They shouldn't be passed on as arguments
  482. to task classes, it's almost always better to re-fetch the object from the
  483. database instead, as there are possible race conditions involved.
  484. Imagine the following scenario where you have an article and a task
  485. that automatically expands some abbreviations in it.
  486. .. code-block:: python
  487. class Article(models.Model):
  488. title = models.CharField()
  489. body = models.TextField()
  490. @task
  491. def expand_abbreviations(article):
  492. article.body.replace("MyCorp", "My Corporation")
  493. article.save()
  494. First, an author creates an article and saves it, then the author
  495. clicks on a button that initiates the abbreviation task.
  496. >>> article = Article.objects.get(id=102)
  497. >>> expand_abbreviations.delay(model_object)
  498. Now, the queue is very busy, so the task won't be run for another 2 minutes,
  499. in the meantime another author makes some changes to the article,
  500. when the task is finally run, the body of the article is reverted to the old
  501. version, because the task had the old body in its argument.
  502. Fixing the race condition is easy, just use the article id instead, and
  503. re-fetch the article in the task body:
  504. .. code-block:: python
  505. @task
  506. def expand_abbreviations(article_id):
  507. article = Article.objects.get(id=article_id)
  508. article.body.replace("MyCorp", "My Corporation")
  509. article.save()
  510. >>> expand_abbreviations(article_id)
  511. There might even be performance benefits to this approach, as sending large
  512. messages may be expensive.
  513. .. _task-database-transactions:
  514. Database transactions
  515. ---------------------
  516. Let's look at another example:
  517. .. code-block:: python
  518. from django.db import transaction
  519. @transaction.commit_on_success
  520. def create_article(request):
  521. article = Article.objects.create(....)
  522. expand_abbreviations.delay(article.pk)
  523. This is a Django view creating an article object in the database,
  524. then passing its primary key to a task. It uses the `commit_on_success`
  525. decorator, which will commit the transaction when the view returns, or
  526. roll back if the view raises an exception.
  527. There is a race condition if the task starts executing
  528. before the transaction has been committed: the database object does not exist
  529. yet!
  530. The solution is to **always commit transactions before applying tasks
  531. that depends on state from the current transaction**:
  532. .. code-block:: python
  533. @transaction.commit_manually
  534. def create_article(request):
  535. try:
  536. article = Article.objects.create(...)
  537. except:
  538. transaction.rollback()
  539. raise
  540. else:
  541. transaction.commit()
  542. expand_abbreviations.delay(article.pk)