tasks.rst 48 KB

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