tasks.rst 48 KB

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