tasks.rst 29 KB

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