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. …
  310. except Exception as exc:
  311. raise self.retry(exc=exc, countdown=60) # override the default and
  312. # retry in 1 minute
  313. .. _task-options:
  314. List of Options
  315. ===============
  316. The task decorator can take a number of options that change the way
  317. the task behaves, for example you can set the rate limit for a task
  318. using the :attr:`rate_limit` option.
  319. Any keyword argument passed to the task decorator will actually be set
  320. as an attribute of the resulting task class, and this is a list
  321. of the built-in attributes.
  322. General
  323. -------
  324. .. _task-general-options:
  325. .. attribute:: Task.name
  326. The name the task is registered as.
  327. You can set this name manually, or a name will be
  328. automatically generated using the module and class name. See
  329. :ref:`task-names`.
  330. .. attribute:: Task.request
  331. If the task is being executed this will contain information
  332. about the current request. Thread local storage is used.
  333. See :ref:`task-request-info`.
  334. .. attribute:: Task.abstract
  335. Abstract classes are not registered, but are used as the
  336. base class for new task types.
  337. .. attribute:: Task.max_retries
  338. The maximum number of attempted retries before giving up.
  339. If the number of retries exceeds this value a :exc:`~@MaxRetriesExceeded`
  340. exception will be raised. *NOTE:* You have to call :meth:`~@Task.retry`
  341. manually, as it will not automatically retry on exception..
  342. The default value is 3.
  343. A value of :const:`None` will disable the retry limit and the
  344. task will retry forever until it succeeds.
  345. .. attribute:: Task.throws
  346. Optional tuple of expected error classes that should not be regarded
  347. as an actual error.
  348. Errors in this list will be reported as a failure to the result backend,
  349. but the worker will not log the event as an error, and no traceback will
  350. be included.
  351. Example:
  352. .. code-block:: python
  353. @task(throws=(KeyError, HttpNotFound)):
  354. def get_foo():
  355. something()
  356. Error types:
  357. - Expected errors (in ``Task.throws``)
  358. Logged with severity ``INFO``, traceback excluded.
  359. - Unexpected errors
  360. Logged with severity ``ERROR``, with traceback included.
  361. .. attribute:: Task.default_retry_delay
  362. Default time in seconds before a retry of the task
  363. should be executed. Can be either :class:`int` or :class:`float`.
  364. Default is a 3 minute delay.
  365. .. attribute:: Task.rate_limit
  366. Set the rate limit for this task type which limits the number of tasks
  367. that can be run in a given time frame. Tasks will still complete when
  368. a rate limit is in effect, but it may take some time before it's allowed to
  369. start.
  370. If this is :const:`None` no rate limit is in effect.
  371. If it is an integer or float, it is interpreted as "tasks per second".
  372. The rate limits can be specified in seconds, minutes or hours
  373. by appending `"/s"`, `"/m"` or `"/h"` to the value. Tasks will be evenly
  374. distributed over the specified time frame.
  375. Example: `"100/m"` (hundred tasks a minute). This will enforce a minimum
  376. delay of 10ms between starting two tasks.
  377. Default is the :setting:`CELERY_DEFAULT_RATE_LIMIT` setting,
  378. which if not specified means rate limiting for tasks is disabled by default.
  379. .. attribute:: Task.time_limit
  380. The hard time limit, in seconds, for this task. If not set then the workers default
  381. will be used.
  382. .. attribute:: Task.soft_time_limit
  383. The soft time limit for this task. If not set then the workers default
  384. will be used.
  385. .. attribute:: Task.ignore_result
  386. Don't store task state. Note that this means you can't use
  387. :class:`~celery.result.AsyncResult` to check if the task is ready,
  388. or get its return value.
  389. .. attribute:: Task.store_errors_even_if_ignored
  390. If :const:`True`, errors will be stored even if the task is configured
  391. to ignore results.
  392. .. attribute:: Task.send_error_emails
  393. Send an email whenever a task of this type fails.
  394. Defaults to the :setting:`CELERY_SEND_TASK_ERROR_EMAILS` setting.
  395. See :ref:`conf-error-mails` for more information.
  396. .. attribute:: Task.ErrorMail
  397. If the sending of error emails is enabled for this task, then
  398. this is the class defining the logic to send error mails.
  399. .. attribute:: Task.serializer
  400. A string identifying the default serialization
  401. method to use. Defaults to the :setting:`CELERY_TASK_SERIALIZER`
  402. setting. Can be `pickle` `json`, `yaml`, or any custom
  403. serialization methods that have been registered with
  404. :mod:`kombu.serialization.registry`.
  405. Please see :ref:`calling-serializers` for more information.
  406. .. attribute:: Task.compression
  407. A string identifying the default compression scheme to use.
  408. Defaults to the :setting:`CELERY_MESSAGE_COMPRESSION` setting.
  409. Can be `gzip`, or `bzip2`, or any custom compression schemes
  410. that have been registered with the :mod:`kombu.compression` registry.
  411. Please see :ref:`calling-compression` for more information.
  412. .. attribute:: Task.backend
  413. The result store backend to use for this task. Defaults to the
  414. :setting:`CELERY_RESULT_BACKEND` setting.
  415. .. attribute:: Task.acks_late
  416. If set to :const:`True` messages for this task will be acknowledged
  417. **after** the task has been executed, not *just before*, which is
  418. the default behavior.
  419. Note that this means the task may be executed twice if the worker
  420. crashes in the middle of execution, which may be acceptable for some
  421. applications.
  422. The global default can be overridden by the :setting:`CELERY_ACKS_LATE`
  423. setting.
  424. .. _task-track-started:
  425. .. attribute:: Task.track_started
  426. If :const:`True` the task will report its status as "started"
  427. when the task is executed by a worker.
  428. The default value is :const:`False` as the normal behaviour is to not
  429. report that level of granularity. Tasks are either pending, finished,
  430. or waiting to be retried. Having a "started" status can be useful for
  431. when there are long running tasks and there is a need to report which
  432. task is currently running.
  433. The host name and process id of the worker executing the task
  434. will be available in the state metadata (e.g. `result.info['pid']`)
  435. The global default can be overridden by the
  436. :setting:`CELERY_TRACK_STARTED` setting.
  437. .. seealso::
  438. The API reference for :class:`~@Task`.
  439. .. _task-states:
  440. States
  441. ======
  442. Celery can keep track of the tasks current state. The state also contains the
  443. result of a successful task, or the exception and traceback information of a
  444. failed task.
  445. There are several *result backends* to choose from, and they all have
  446. different strengths and weaknesses (see :ref:`task-result-backends`).
  447. During its lifetime a task will transition through several possible states,
  448. and each state may have arbitrary metadata attached to it. When a task
  449. moves into a new state the previous state is
  450. forgotten about, but some transitions can be deducted, (e.g. a task now
  451. in the :state:`FAILED` state, is implied to have been in the
  452. :state:`STARTED` state at some point).
  453. There are also sets of states, like the set of
  454. :state:`FAILURE_STATES`, and the set of :state:`READY_STATES`.
  455. The client uses the membership of these sets to decide whether
  456. the exception should be re-raised (:state:`PROPAGATE_STATES`), or whether
  457. the state can be cached (it can if the task is ready).
  458. You can also define :ref:`custom-states`.
  459. .. _task-result-backends:
  460. Result Backends
  461. ---------------
  462. If you want to keep track of tasks or need the return values, then Celery
  463. must store or send the states somewhere so that they can be retrieved later.
  464. There are several built-in result backends to choose from: SQLAlchemy/Django ORM,
  465. Memcached, RabbitMQ (amqp), MongoDB, and Redis -- or you can define your own.
  466. No backend works well for every use case.
  467. You should read about the strengths and weaknesses of each backend, and choose
  468. the most appropriate for your needs.
  469. .. seealso::
  470. :ref:`conf-result-backend`
  471. RabbitMQ Result Backend
  472. ~~~~~~~~~~~~~~~~~~~~~~~
  473. The RabbitMQ result backend (amqp) is special as it does not actually *store*
  474. the states, but rather sends them as messages. This is an important difference as it
  475. means that a result *can only be retrieved once*; If you have two processes
  476. waiting for the same result, one of the processes will never receive the
  477. result!
  478. Even with that limitation, it is an excellent choice if you need to receive
  479. state changes in real-time. Using messaging means the client does not have to
  480. poll for new states.
  481. There are several other pitfalls you should be aware of when using the
  482. RabbitMQ result backend:
  483. * Every new task creates a new queue on the server, with thousands of tasks
  484. the broker may be overloaded with queues and this will affect performance in
  485. negative ways. If you're using RabbitMQ then each queue will be a separate
  486. Erlang process, so if you're planning to keep many results simultaneously you
  487. may have to increase the Erlang process limit, and the maximum number of file
  488. descriptors your OS allows.
  489. * Old results will be cleaned automatically, based on the
  490. :setting:`CELERY_TASK_RESULT_EXPIRES` setting. By default this is set to
  491. expire after 1 day: if you have a very busy cluster you should lower
  492. this value.
  493. For a list of options supported by the RabbitMQ result backend, please see
  494. :ref:`conf-amqp-result-backend`.
  495. Database Result Backend
  496. ~~~~~~~~~~~~~~~~~~~~~~~
  497. Keeping state in the database can be convenient for many, especially for
  498. web applications with a database already in place, but it also comes with
  499. limitations.
  500. * Polling the database for new states is expensive, and so you should
  501. increase the polling intervals of operations such as `result.get()`.
  502. * Some databases use a default transaction isolation level that
  503. is not suitable for polling tables for changes.
  504. In MySQL the default transaction isolation level is `REPEATABLE-READ`, which
  505. means the transaction will not see changes by other transactions until the
  506. transaction is committed. It is recommended that you change to the
  507. `READ-COMMITTED` isolation level.
  508. .. _task-builtin-states:
  509. Built-in States
  510. ---------------
  511. .. state:: PENDING
  512. PENDING
  513. ~~~~~~~
  514. Task is waiting for execution or unknown.
  515. Any task id that is not known is implied to be in the pending state.
  516. .. state:: STARTED
  517. STARTED
  518. ~~~~~~~
  519. Task has been started.
  520. Not reported by default, to enable please see :attr:`@Task.track_started`.
  521. :metadata: `pid` and `hostname` of the worker process executing
  522. the task.
  523. .. state:: SUCCESS
  524. SUCCESS
  525. ~~~~~~~
  526. Task has been successfully executed.
  527. :metadata: `result` contains the return value of the task.
  528. :propagates: Yes
  529. :ready: Yes
  530. .. state:: FAILURE
  531. FAILURE
  532. ~~~~~~~
  533. Task execution resulted in failure.
  534. :metadata: `result` contains the exception occurred, and `traceback`
  535. contains the backtrace of the stack at the point when the
  536. exception was raised.
  537. :propagates: Yes
  538. .. state:: RETRY
  539. RETRY
  540. ~~~~~
  541. Task is being retried.
  542. :metadata: `result` contains the exception that caused the retry,
  543. and `traceback` contains the backtrace of the stack at the point
  544. when the exceptions was raised.
  545. :propagates: No
  546. .. state:: REVOKED
  547. REVOKED
  548. ~~~~~~~
  549. Task has been revoked.
  550. :propagates: Yes
  551. .. _custom-states:
  552. Custom states
  553. -------------
  554. You can easily define your own states, all you need is a unique name.
  555. The name of the state is usually an uppercase string. As an example
  556. you could have a look at :mod:`abortable tasks <~celery.contrib.abortable>`
  557. which defines its own custom :state:`ABORTED` state.
  558. Use :meth:`~@Task.update_state` to update a task's state::
  559. @app.task(bind=True)
  560. def upload_files(self, filenames):
  561. for i, file in enumerate(filenames):
  562. self.update_state(state='PROGRESS',
  563. meta={'current': i, 'total': len(filenames)})
  564. Here I created the state `"PROGRESS"`, which tells any application
  565. aware of this state that the task is currently in progress, and also where
  566. it is in the process by having `current` and `total` counts as part of the
  567. state metadata. This can then be used to create e.g. progress bars.
  568. .. _pickling_exceptions:
  569. Creating pickleable exceptions
  570. ------------------------------
  571. A rarely known Python fact is that exceptions must conform to some
  572. simple rules to support being serialized by the pickle module.
  573. Tasks that raise exceptions that are not pickleable will not work
  574. properly when Pickle is used as the serializer.
  575. To make sure that your exceptions are pickleable the exception
  576. *MUST* provide the original arguments it was instantiated
  577. with in its ``.args`` attribute. The simplest way
  578. to ensure this is to have the exception call ``Exception.__init__``.
  579. Let's look at some examples that work, and one that doesn't:
  580. .. code-block:: python
  581. # OK:
  582. class HttpError(Exception):
  583. pass
  584. # BAD:
  585. class HttpError(Exception):
  586. def __init__(self, status_code):
  587. self.status_code = status_code
  588. # OK:
  589. class HttpError(Exception):
  590. def __init__(self, status_code):
  591. self.status_code = status_code
  592. Exception.__init__(self, status_code) # <-- REQUIRED
  593. So the rule is:
  594. For any exception that supports custom arguments ``*args``,
  595. ``Exception.__init__(self, *args)`` must be used.
  596. There is no special support for *keyword arguments*, so if you
  597. want to preserve keyword arguments when the exception is unpickled
  598. you have to pass them as regular args:
  599. .. code-block:: python
  600. class HttpError(Exception):
  601. def __init__(self, status_code, headers=None, body=None):
  602. self.status_code = status_code
  603. self.headers = headers
  604. self.body = body
  605. super(HttpError, self).__init__(status_code, headers, body)
  606. .. _task-semipredicates:
  607. Semipredicates
  608. ==============
  609. The worker wraps the task in a tracing function which records the final
  610. state of the task. There are a number of exceptions that can be used to
  611. signal this function to change how it treats the return of the task.
  612. .. _task-semipred-ignore:
  613. Ignore
  614. ------
  615. The task may raise :exc:`~@Ignore` to force the worker to ignore the
  616. task. This means that no state will be recorded for the task, but the
  617. message is still acknowledged (removed from queue).
  618. This can be used if you want to implement custom revoke-like
  619. functionality, or manually store the result of a task.
  620. Example keeping revoked tasks in a Redis set:
  621. .. code-block:: python
  622. from celery.exceptions import Ignore
  623. @app.task(bind=True)
  624. def some_task(self):
  625. if redis.ismember('tasks.revoked', self.request.id):
  626. raise Ignore()
  627. Example that stores results manually:
  628. .. code-block:: python
  629. from celery import states
  630. from celery.exceptions import Ignore
  631. @app.task(bind=True)
  632. def get_tweets(self, user):
  633. timeline = twitter.get_timeline(user)
  634. self.update_state(state=states.SUCCESS, meta=timeline)
  635. raise Ignore()
  636. .. _task-semipred-reject:
  637. Reject
  638. ------
  639. The task may raise :exc:`~@Reject` to reject the task message using
  640. AMQPs ``basic_reject`` method. This will not have any effect unless
  641. :attr:`Task.acks_late` is enabled.
  642. Rejecting a message has the same effect as acking it, but some
  643. brokers may implement additional functionality that can be used.
  644. For example RabbitMQ supports the concept of `Dead Letter Exchanges`_
  645. where a queue can be configured to use a dead letter exchange that rejected
  646. messages are redelivered to.
  647. .. _`Dead Letter Exchanges`: http://www.rabbitmq.com/dlx.html
  648. Reject can also be used to requeue messages, but please be very careful
  649. when using this as it can easily result in an infinite message loop.
  650. Example using reject when a task causes an out of memory condition:
  651. .. code-block:: python
  652. import errno
  653. from celery.exceptions import Reject
  654. @app.task(bind=True, acks_late=True)
  655. def render_scene(self, path):
  656. file = get_file(path)
  657. try:
  658. renderer.render_scene(file)
  659. # if the file is too big to fit in memory
  660. # we reject it so that it's redelivered to the dead letter exchange
  661. # and we can manually inspect the situation.
  662. except MemoryError as exc:
  663. raise Reject(exc, requeue=False)
  664. except OSError as exc:
  665. if exc.errno == errno.ENOMEM:
  666. raise Reject(exc, requeue=False)
  667. # For any other error we retry after 10 seconds.
  668. except Exception as exc:
  669. raise self.retry(exc, countdown=10)
  670. Example requeuing the message:
  671. .. code-block:: python
  672. from celery.exceptions import Reject
  673. @app.task(bind=True, acks_late=True)
  674. def requeues(self):
  675. if not self.request.delivery_info['redelivered']:
  676. raise Reject('no reason', requeue=True)
  677. print('received two times')
  678. Consult your broker documentation for more details about the ``basic_reject``
  679. method.
  680. .. _task-semipred-retry:
  681. Retry
  682. -----
  683. The :exc:`~@Retry` exception is raised by the ``Task.retry`` method
  684. to tell the worker that the task is being retried.
  685. .. _task-custom-classes:
  686. Custom task classes
  687. ===================
  688. All tasks inherit from the :class:`@Task` class.
  689. The :meth:`~@Task.run` method becomes the task body.
  690. As an example, the following code,
  691. .. code-block:: python
  692. @app.task
  693. def add(x, y):
  694. return x + y
  695. will do roughly this behind the scenes:
  696. .. code-block:: python
  697. class _AddTask(app.Task):
  698. def run(self, x, y):
  699. return x + y
  700. add = app.tasks[_AddTask.name]
  701. Instantiation
  702. -------------
  703. A task is **not** instantiated for every request, but is registered
  704. in the task registry as a global instance.
  705. This means that the ``__init__`` constructor will only be called
  706. once per process, and that the task class is semantically closer to an
  707. Actor.
  708. If you have a task,
  709. .. code-block:: python
  710. from celery import Task
  711. class NaiveAuthenticateServer(Task):
  712. def __init__(self):
  713. self.users = {'george': 'password'}
  714. def run(self, username, password):
  715. try:
  716. return self.users[username] == password
  717. except KeyError:
  718. return False
  719. And you route every request to the same process, then it
  720. will keep state between requests.
  721. This can also be useful to cache resources,
  722. e.g. a base Task class that caches a database connection:
  723. .. code-block:: python
  724. from celery import Task
  725. class DatabaseTask(Task):
  726. abstract = True
  727. _db = None
  728. @property
  729. def db(self):
  730. if self._db is None:
  731. self._db = Database.connect()
  732. return self._db
  733. that can be added to tasks like this:
  734. .. code-block:: python
  735. @app.task(base=DatabaseTask)
  736. def process_rows():
  737. for row in process_rows.db.table.all():
  738. …
  739. The ``db`` attribute of the ``process_rows`` task will then
  740. always stay the same in each process.
  741. Abstract classes
  742. ----------------
  743. Abstract classes are not registered, but are used as the
  744. base class for new task types.
  745. .. code-block:: python
  746. from celery import Task
  747. class DebugTask(Task):
  748. abstract = True
  749. def after_return(self, *args, **kwargs):
  750. print('Task returned: {0!r}'.format(self.request)
  751. @app.task(base=DebugTask)
  752. def add(x, y):
  753. return x + y
  754. Handlers
  755. --------
  756. .. method:: after_return(self, status, retval, task_id, args, kwargs, einfo)
  757. Handler called after the task returns.
  758. :param status: Current task state.
  759. :param retval: Task return value/exception.
  760. :param task_id: Unique id of the task.
  761. :param args: Original arguments for the task that returned.
  762. :param kwargs: Original keyword arguments for the task
  763. that returned.
  764. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  765. instance, containing the traceback (if any).
  766. The return value of this handler is ignored.
  767. .. method:: on_failure(self, exc, task_id, args, kwargs, einfo)
  768. This is run by the worker when the task fails.
  769. :param exc: The exception raised by the task.
  770. :param task_id: Unique id of the failed task.
  771. :param args: Original arguments for the task that failed.
  772. :param kwargs: Original keyword arguments for the task
  773. that failed.
  774. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  775. instance, containing the traceback.
  776. The return value of this handler is ignored.
  777. .. method:: on_retry(self, exc, task_id, args, kwargs, einfo)
  778. This is run by the worker when the task is to be retried.
  779. :param exc: The exception sent to :meth:`~@Task.retry`.
  780. :param task_id: Unique id of the retried task.
  781. :param args: Original arguments for the retried task.
  782. :param kwargs: Original keyword arguments for the retried task.
  783. :keyword einfo: :class:`~celery.datastructures.ExceptionInfo`
  784. instance, containing the traceback.
  785. The return value of this handler is ignored.
  786. .. method:: on_success(self, retval, task_id, args, kwargs)
  787. Run by the worker if the task executes successfully.
  788. :param retval: The return value of the task.
  789. :param task_id: Unique id of the executed task.
  790. :param args: Original arguments for the executed task.
  791. :param kwargs: Original keyword arguments for the executed task.
  792. The return value of this handler is ignored.
  793. on_retry
  794. ~~~~~~~~
  795. .. _task-how-they-work:
  796. How it works
  797. ============
  798. Here comes the technical details, this part isn't something you need to know,
  799. but you may be interested.
  800. All defined tasks are listed in a registry. The registry contains
  801. a list of task names and their task classes. You can investigate this registry
  802. yourself:
  803. .. code-block:: python
  804. >>> from proj.celery import app
  805. >>> app.tasks
  806. {'celery.chord_unlock':
  807. <@task: celery.chord_unlock>,
  808. 'celery.backend_cleanup':
  809. <@task: celery.backend_cleanup>,
  810. 'celery.chord':
  811. <@task: celery.chord>}
  812. This is the list of tasks built-in to celery. Note that tasks
  813. will only be registered when the module they are defined in is imported.
  814. The default loader imports any modules listed in the
  815. :setting:`CELERY_IMPORTS` setting.
  816. The entity responsible for registering your task in the registry is the
  817. metaclass: :class:`~celery.task.base.TaskType`.
  818. If you want to register your task manually you can mark the
  819. task as :attr:`~@Task.abstract`:
  820. .. code-block:: python
  821. class MyTask(Task):
  822. abstract = True
  823. This way the task won't be registered, but any task inheriting from
  824. it will be.
  825. When tasks are sent, no actual function code is sent with it, just the name
  826. of the task to execute. When the worker then receives the message it can look
  827. up the name in its task registry to find the execution code.
  828. This means that your workers should always be updated with the same software
  829. as the client. This is a drawback, but the alternative is a technical
  830. challenge that has yet to be solved.
  831. .. _task-best-practices:
  832. Tips and Best Practices
  833. =======================
  834. .. _task-ignore_results:
  835. Ignore results you don't want
  836. -----------------------------
  837. If you don't care about the results of a task, be sure to set the
  838. :attr:`~@Task.ignore_result` option, as storing results
  839. wastes time and resources.
  840. .. code-block:: python
  841. @app.task(ignore_result=True)
  842. def mytask(…):
  843. something()
  844. Results can even be disabled globally using the :setting:`CELERY_IGNORE_RESULT`
  845. setting.
  846. .. _task-disable-rate-limits:
  847. Disable rate limits if they're not used
  848. ---------------------------------------
  849. Disabling rate limits altogether is recommended if you don't have
  850. any tasks using them. This is because the rate limit subsystem introduces
  851. quite a lot of complexity.
  852. Set the :setting:`CELERY_DISABLE_RATE_LIMITS` setting to globally disable
  853. rate limits:
  854. .. code-block:: python
  855. CELERY_DISABLE_RATE_LIMITS = True
  856. You find additional optimization tips in the
  857. :ref:`Optimizing Guide <guide-optimizing>`.
  858. .. _task-synchronous-subtasks:
  859. Avoid launching synchronous subtasks
  860. ------------------------------------
  861. Having a task wait for the result of another task is really inefficient,
  862. and may even cause a deadlock if the worker pool is exhausted.
  863. Make your design asynchronous instead, for example by using *callbacks*.
  864. **Bad**:
  865. .. code-block:: python
  866. @app.task
  867. def update_page_info(url):
  868. page = fetch_page.delay(url).get()
  869. info = parse_page.delay(url, page).get()
  870. store_page_info.delay(url, info)
  871. @app.task
  872. def fetch_page(url):
  873. return myhttplib.get(url)
  874. @app.task
  875. def parse_page(url, page):
  876. return myparser.parse_document(page)
  877. @app.task
  878. def store_page_info(url, info):
  879. return PageInfo.objects.create(url, info)
  880. **Good**:
  881. .. code-block:: python
  882. def update_page_info(url):
  883. # fetch_page -> parse_page -> store_page
  884. chain = fetch_page.s() | parse_page.s() | store_page_info.s(url)
  885. chain()
  886. @app.task()
  887. def fetch_page(url):
  888. return myhttplib.get(url)
  889. @app.task()
  890. def parse_page(page):
  891. return myparser.parse_document(page)
  892. @app.task(ignore_result=True)
  893. def store_page_info(info, url):
  894. PageInfo.objects.create(url=url, info=info)
  895. Here I instead created a chain of tasks by linking together
  896. different :func:`~celery.signature`'s.
  897. You can read about chains and other powerful constructs
  898. at :ref:`designing-workflows`.
  899. .. _task-performance-and-strategies:
  900. Performance and Strategies
  901. ==========================
  902. .. _task-granularity:
  903. Granularity
  904. -----------
  905. The task granularity is the amount of computation needed by each subtask.
  906. In general it is better to split the problem up into many small tasks, than
  907. have a few long running tasks.
  908. With smaller tasks you can process more tasks in parallel and the tasks
  909. won't run long enough to block the worker from processing other waiting tasks.
  910. However, executing a task does have overhead. A message needs to be sent, data
  911. may not be local, etc. So if the tasks are too fine-grained the additional
  912. overhead may not be worth it in the end.
  913. .. seealso::
  914. The book `Art of Concurrency`_ has a section dedicated to the topic
  915. of task granularity [AOC1]_.
  916. .. _`Art of Concurrency`: http://oreilly.com/catalog/9780596521547
  917. .. [AOC1] Breshears, Clay. Section 2.2.1, "The Art of Concurrency".
  918. O'Reilly Media, Inc. May 15, 2009. ISBN-13 978-0-596-52153-0.
  919. .. _task-data-locality:
  920. Data locality
  921. -------------
  922. The worker processing the task should be as close to the data as
  923. possible. The best would be to have a copy in memory, the worst would be a
  924. full transfer from another continent.
  925. If the data is far away, you could try to run another worker at location, or
  926. if that's not possible - cache often used data, or preload data you know
  927. is going to be used.
  928. The easiest way to share data between workers is to use a distributed cache
  929. system, like `memcached`_.
  930. .. seealso::
  931. The paper `Distributed Computing Economics`_ by Jim Gray is an excellent
  932. introduction to the topic of data locality.
  933. .. _`Distributed Computing Economics`:
  934. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  935. .. _`memcached`: http://memcached.org/
  936. .. _task-state:
  937. State
  938. -----
  939. Since celery is a distributed system, you can't know in which process, or
  940. on what machine the task will be executed. You can't even know if the task will
  941. run in a timely manner.
  942. The ancient async sayings tells us that “asserting the world is the
  943. responsibility of the task”. What this means is that the world view may
  944. have changed since the task was requested, so the task is responsible for
  945. making sure the world is how it should be; If you have a task
  946. that re-indexes a search engine, and the search engine should only be
  947. re-indexed at maximum every 5 minutes, then it must be the tasks
  948. responsibility to assert that, not the callers.
  949. Another gotcha is Django model objects. They shouldn't be passed on as
  950. arguments to tasks. It's almost always better to re-fetch the object from
  951. the database when the task is running instead, as using old data may lead
  952. to race conditions.
  953. Imagine the following scenario where you have an article and a task
  954. that automatically expands some abbreviations in it:
  955. .. code-block:: python
  956. class Article(models.Model):
  957. title = models.CharField()
  958. body = models.TextField()
  959. @app.task
  960. def expand_abbreviations(article):
  961. article.body.replace('MyCorp', 'My Corporation')
  962. article.save()
  963. First, an author creates an article and saves it, then the author
  964. clicks on a button that initiates the abbreviation task::
  965. >>> article = Article.objects.get(id=102)
  966. >>> expand_abbreviations.delay(article)
  967. Now, the queue is very busy, so the task won't be run for another 2 minutes.
  968. In the meantime another author makes changes to the article, so
  969. when the task is finally run, the body of the article is reverted to the old
  970. version because the task had the old body in its argument.
  971. Fixing the race condition is easy, just use the article id instead, and
  972. re-fetch the article in the task body:
  973. .. code-block:: python
  974. @app.task
  975. def expand_abbreviations(article_id):
  976. article = Article.objects.get(id=article_id)
  977. article.body.replace('MyCorp', 'My Corporation')
  978. article.save()
  979. >>> expand_abbreviations(article_id)
  980. There might even be performance benefits to this approach, as sending large
  981. messages may be expensive.
  982. .. _task-database-transactions:
  983. Database transactions
  984. ---------------------
  985. Let's have a look at another example:
  986. .. code-block:: python
  987. from django.db import transaction
  988. @transaction.commit_on_success
  989. def create_article(request):
  990. article = Article.objects.create(…)
  991. expand_abbreviations.delay(article.pk)
  992. This is a Django view creating an article object in the database,
  993. then passing the primary key to a task. It uses the `commit_on_success`
  994. decorator, which will commit the transaction when the view returns, or
  995. roll back if the view raises an exception.
  996. There is a race condition if the task starts executing
  997. before the transaction has been committed; The database object does not exist
  998. yet!
  999. The solution is to *always commit transactions before sending tasks
  1000. depending on state from the current transaction*:
  1001. .. code-block:: python
  1002. @transaction.commit_manually
  1003. def create_article(request):
  1004. try:
  1005. article = Article.objects.create(…)
  1006. except:
  1007. transaction.rollback()
  1008. raise
  1009. else:
  1010. transaction.commit()
  1011. expand_abbreviations.delay(article.pk)
  1012. .. _task-example:
  1013. Example
  1014. =======
  1015. Let's take a real wold example; A blog where comments posted needs to be
  1016. filtered for spam. When the comment is created, the spam filter runs in the
  1017. background, so the user doesn't have to wait for it to finish.
  1018. I have a Django blog application allowing comments
  1019. on blog posts. I'll describe parts of the models/views and tasks for this
  1020. application.
  1021. blog/models.py
  1022. --------------
  1023. The comment model looks like this:
  1024. .. code-block:: python
  1025. from django.db import models
  1026. from django.utils.translation import ugettext_lazy as _
  1027. class Comment(models.Model):
  1028. name = models.CharField(_('name'), max_length=64)
  1029. email_address = models.EmailField(_('email address'))
  1030. homepage = models.URLField(_('home page'),
  1031. blank=True, verify_exists=False)
  1032. comment = models.TextField(_('comment'))
  1033. pub_date = models.DateTimeField(_('Published date'),
  1034. editable=False, auto_add_now=True)
  1035. is_spam = models.BooleanField(_('spam?'),
  1036. default=False, editable=False)
  1037. class Meta:
  1038. verbose_name = _('comment')
  1039. verbose_name_plural = _('comments')
  1040. In the view where the comment is posted, I first write the comment
  1041. to the database, then I launch the spam filter task in the background.
  1042. .. _task-example-blog-views:
  1043. blog/views.py
  1044. -------------
  1045. .. code-block:: python
  1046. from django import forms
  1047. from django.http import HttpResponseRedirect
  1048. from django.template.context import RequestContext
  1049. from django.shortcuts import get_object_or_404, render_to_response
  1050. from blog import tasks
  1051. from blog.models import Comment
  1052. class CommentForm(forms.ModelForm):
  1053. class Meta:
  1054. model = Comment
  1055. def add_comment(request, slug, template_name='comments/create.html'):
  1056. post = get_object_or_404(Entry, slug=slug)
  1057. remote_addr = request.META.get('REMOTE_ADDR')
  1058. if request.method == 'post':
  1059. form = CommentForm(request.POST, request.FILES)
  1060. if form.is_valid():
  1061. comment = form.save()
  1062. # Check spam asynchronously.
  1063. tasks.spam_filter.delay(comment_id=comment.id,
  1064. remote_addr=remote_addr)
  1065. return HttpResponseRedirect(post.get_absolute_url())
  1066. else:
  1067. form = CommentForm()
  1068. context = RequestContext(request, {'form': form})
  1069. return render_to_response(template_name, context_instance=context)
  1070. To filter spam in comments I use `Akismet`_, the service
  1071. used to filter spam in comments posted to the free weblog platform
  1072. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  1073. need to pay. You have to sign up to their service to get an API key.
  1074. To make API calls to `Akismet`_ I use the `akismet.py`_ library written by
  1075. `Michael Foord`_.
  1076. .. _task-example-blog-tasks:
  1077. blog/tasks.py
  1078. -------------
  1079. .. code-block:: python
  1080. from celery import Celery
  1081. from akismet import Akismet
  1082. from django.core.exceptions import ImproperlyConfigured
  1083. from django.contrib.sites.models import Site
  1084. from blog.models import Comment
  1085. app = Celery(broker='amqp://')
  1086. @app.task
  1087. def spam_filter(comment_id, remote_addr=None):
  1088. logger = spam_filter.get_logger()
  1089. logger.info('Running spam filter for comment %s', comment_id)
  1090. comment = Comment.objects.get(pk=comment_id)
  1091. current_domain = Site.objects.get_current().domain
  1092. akismet = Akismet(settings.AKISMET_KEY, 'http://{0}'.format(domain))
  1093. if not akismet.verify_key():
  1094. raise ImproperlyConfigured('Invalid AKISMET_KEY')
  1095. is_spam = akismet.comment_check(user_ip=remote_addr,
  1096. comment_content=comment.comment,
  1097. comment_author=comment.name,
  1098. comment_author_email=comment.email_address)
  1099. if is_spam:
  1100. comment.is_spam = True
  1101. comment.save()
  1102. return is_spam
  1103. .. _`Akismet`: http://akismet.com/faq/
  1104. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
  1105. .. _`Michael Foord`: http://www.voidspace.org.uk/