tasks.rst 49 KB

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