tasks.rst 46 KB

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