tasks.rst 24 KB

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