tasks.rst 28 KB

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