tasks.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. .. _guide-tasks:
  2. =======
  3. Tasks
  4. =======
  5. .. contents::
  6. :local:
  7. .. _task-basics:
  8. Basics
  9. ======
  10. A task is a class that encapsulates a function and its execution options.
  11. Given a function ``create_user``, that takes two arguments: ``username`` and
  12. ``password``, you can create a task like this:
  13. .. code-block:: python
  14. from celery.task import Task
  15. from django.contrib.auth import User
  16. class CreateUserTask(Task):
  17. def run(self, username, password):
  18. User.objects.create(username=username, password=password)
  19. For convenience there is a shortcut decorator that turns any function into
  20. a task:
  21. .. code-block:: python
  22. from celery.decorators import task
  23. from django.contrib.auth import User
  24. @task
  25. def create_user(username, password):
  26. User.objects.create(username=username, password=password)
  27. The task decorator takes the same execution options as the
  28. :class:`~celery.task.base.Task` class does:
  29. .. code-block:: python
  30. @task(serializer="json")
  31. def create_user(username, password):
  32. User.objects.create(username=username, password=password)
  33. .. _task-keyword-arguments:
  34. Default keyword arguments
  35. =========================
  36. Celery supports a set of default arguments that can be forwarded to any task.
  37. Tasks can choose not to take these, or list the ones they want.
  38. The worker will do the right thing.
  39. The current default keyword arguments are:
  40. :task_id: The unique id of the executing task.
  41. :task_name: Name of the currently executing task.
  42. :task_retries: How many times the current task has been retried.
  43. An integer starting at ``0``.
  44. :task_is_eager: Set to :const:`True` if the task is executed locally in
  45. the client, kand not by a worker.
  46. :logfile: The log file, can be passed on to
  47. :meth:`~celery.task.base.Task.get_logger` to gain access to
  48. the workers log file. See `Logging`_.
  49. :loglevel: The current loglevel used.
  50. :delivery_info: Additional message delivery information. This is a mapping
  51. containing the exchange and routing key used to deliver this
  52. task. It's used by e.g. :meth:`~celery.task.base.Task.retry`
  53. to resend the task to the same destination queue.
  54. **NOTE** As some messaging backends doesn't have advanced routing
  55. capabilities, you can't trust the availability of keys in this mapping.
  56. .. _task-logging:
  57. Logging
  58. =======
  59. You can use the workers logger to add diagnostic output to
  60. the worker log:
  61. .. code-block:: python
  62. class AddTask(Task):
  63. def run(self, x, y, **kwargs):
  64. logger = self.get_logger(**kwargs)
  65. logger.info("Adding %s + %s" % (x, y))
  66. return x + y
  67. or using the decorator syntax:
  68. .. code-block:: python
  69. @task()
  70. def add(x, y, **kwargs):
  71. logger = add.get_logger(**kwargs)
  72. logger.info("Adding %s + %s" % (x, y))
  73. return x + y
  74. There are several logging levels available, and the workers ``loglevel``
  75. setting decides whether or not they will be written to the log file.
  76. Of course, you can also simply use ``print`` as anything written to standard
  77. out/-err will be written to the logfile as well.
  78. .. _task-retry:
  79. Retrying a task if something fails
  80. ==================================
  81. Simply use :meth:`~celery.task.base.Task.retry` to re-send the task.
  82. It will do the right thing, and respect the
  83. :attr:`~celery.task.base.Task.max_retries` attribute:
  84. .. code-block:: python
  85. @task()
  86. def send_twitter_status(oauth, tweet, **kwargs):
  87. try:
  88. twitter = Twitter(oauth)
  89. twitter.update_status(tweet)
  90. except (Twitter.FailWhaleError, Twitter.LoginError), exc:
  91. send_twitter_status.retry(args=[oauth, tweet], kwargs=kwargs, exc=exc)
  92. Here we used the ``exc`` argument to pass the current exception to
  93. :meth:`~celery.task.base.Task.retry`. At each step of the retry this exception
  94. is available as the tombstone (result) of the task. When
  95. :attr:`~celery.task.base.Task.max_retries` has been exceeded this is the
  96. exception raised. However, if an ``exc`` argument is not provided the
  97. :exc:`~celery.exceptions.RetryTaskError` exception is raised instead.
  98. **Important note:** The task has to take the magic keyword arguments
  99. in order for max retries to work properly, this is because it keeps track
  100. of the current number of retries using the ``task_retries`` keyword argument
  101. passed on to the task. In addition, it also uses the ``task_id`` keyword
  102. argument to use the same task id, and ``delivery_info`` to route the
  103. retried task to the same destination.
  104. .. _task-retry-custom-delay:
  105. Using a custom retry delay
  106. --------------------------
  107. When a task is to be retried, it will wait for a given amount of time
  108. before doing so. The default delay is in the
  109. :attr:`~celery.task.base.Task.default_retry_delay`
  110. attribute on the task. By default this is set to 3 minutes. Note that the
  111. unit for setting the delay is in seconds (int or float).
  112. You can also provide the ``countdown`` argument to
  113. :meth:`~celery.task.base.Task.retry` to override this default.
  114. .. code-block:: python
  115. class MyTask(Task):
  116. default_retry_delay = 30 * 60 # retry in 30 minutes
  117. def run(self, x, y, **kwargs):
  118. try:
  119. ...
  120. except Exception, exc:
  121. self.retry([x, y], kwargs, exc=exc,
  122. countdown=60) # override the default and
  123. # - retry in 1 minute
  124. .. _task-options:
  125. Task options
  126. ============
  127. General
  128. -------
  129. .. _task-general-options:
  130. .. attribute:: Task.name
  131. The name the task is registered as.
  132. You can set this name manually, or just use the default which is
  133. automatically generated using the module and class name.
  134. .. attribute:: Task.abstract
  135. Abstract classes are not registered, but are used as the
  136. superclass when making new task types by subclassing.
  137. .. attribute:: Task.max_retries
  138. The maximum number of attempted retries before giving up.
  139. If this exceeds the :exc:`~celery.exceptions.MaxRetriesExceeded`
  140. an exception will be raised. *NOTE:* You have to :meth:`retry`
  141. manually, it's not something that happens automatically.
  142. .. attribute:: Task.default_retry_delay
  143. Default time in seconds before a retry of the task
  144. should be executed. Can be either an ``int`` or a ``float``.
  145. Default is a 3 minute delay.
  146. .. attribute:: Task.rate_limit
  147. Set the rate limit for this task type, i.e. how many times in
  148. a given period of time is the task allowed to run.
  149. If this is :const:`None` no rate limit is in effect.
  150. If it is an integer, it is interpreted as "tasks per second".
  151. The rate limits can be specified in seconds, minutes or hours
  152. by appending ``"/s"``, ``"/m"`` or ``"/h"`` to the value.
  153. Example: ``"100/m"`` (hundred tasks a minute). Default is the
  154. :setting:`CELERY_DEFAULT_RATE_LIMIT` setting, which if not specified means
  155. rate limiting for tasks is turned off by default.
  156. .. attribute:: Task.ignore_result
  157. Don't store task state. This means you can't use the
  158. :class:`~celery.result.AsyncResult` to check if the task is ready,
  159. or get its return value.
  160. .. attribute:: Task.store_errors_even_if_ignored
  161. If true, errors will be stored even if the task is configured
  162. to ignore results.
  163. .. attribute:: Task.send_error_emails
  164. Send an e-mail whenever a task of this type fails.
  165. Defaults to the :setting:`CELERY_SEND_TASK_ERROR_EMAILS` setting.
  166. See :ref:`conf-error-mails` for more information.
  167. .. attribute:: Task.error_whitelist
  168. If the sending of error e-emails is enabled for this task, then
  169. this is a whitelist of exceptions to actually send e-mails about.
  170. .. attribute:: Task.serializer
  171. A string identifying the default serialization
  172. method to use. Defaults to the :setting:`CELERY_TASK_SERIALIZER`
  173. setting. Can be ``pickle`` ``json``, ``yaml``, or any custom
  174. serialization methods that have been registered with
  175. :mod:`carrot.serialization.registry`.
  176. Please see :ref:`executing-serializers` for more information.
  177. .. attribute:: Task.backend
  178. The result store backend to use for this task. Defaults to the
  179. :setting:`CELERY_RESULT_BACKEND` setting.
  180. .. attribute:: Task.acks_late
  181. If set to :const:`True` messages for this task will be acknowledged
  182. **after** the task has been executed, not *just before*, which is
  183. the default behavior.
  184. Note that this means the task may be executed twice if the worker
  185. crashes in the middle of execution, which may be acceptable for some
  186. applications.
  187. The global default can be overriden by the :setting:`CELERY_ACKS_LATE`
  188. setting.
  189. .. _task-track-started:
  190. .. attribute:: Task.track_started
  191. If :const:`True` the task will report its status as "started"
  192. when the task is executed by a worker.
  193. The default value is ``False`` as the normal behaviour is to not
  194. report that level of granularity. Tasks are either pending, finished,
  195. or waiting to be retried. Having a "started" status can be useful for
  196. when there are long running tasks and there is a need to report which
  197. task is currently running.
  198. The global default can be overridden by the
  199. :setting:`CELERY_TRACK_STARTED` setting.
  200. .. seealso::
  201. The API reference for :class:`~celery.task.base.Task`.
  202. .. _task-message-options:
  203. Message and routing options
  204. ---------------------------
  205. .. attribute:: Task.queue
  206. Use the routing settings from a queue defined in :setting:`CELERY_QUEUES`.
  207. If defined the :attr:`exchange` and :attr:`routing_key` options will be
  208. ignored.
  209. .. attribute:: Task.exchange
  210. Override the global default ``exchange`` for this task.
  211. .. attribute:: Task.routing_key
  212. Override the global default ``routing_key`` for this task.
  213. .. attribute:: Task.mandatory
  214. If set, the task message has mandatory routing. By default the task
  215. is silently dropped by the broker if it can't be routed to a queue.
  216. However -- If the task is mandatory, an exception will be raised
  217. instead.
  218. .. attribute:: Task.immediate
  219. Request immediate delivery. If the task cannot be routed to a
  220. task worker immediately, an exception will be raised. This is
  221. instead of the default behavior, where the broker will accept and
  222. queue the task, but with no guarantee that the task will ever
  223. be executed.
  224. .. attribute:: Task.priority
  225. The message priority. A number from 0 to 9, where 0 is the
  226. highest priority. **Note:** At the time writing this, RabbitMQ did not yet support
  227. priorities
  228. .. seealso::
  229. :ref:`executing-routing` for more information about message options,
  230. and :ref:`guide-routing`.
  231. .. _task-states:
  232. Task States
  233. ===========
  234. A task can be in several states, and each state can have arbitrary metadata
  235. attached to it. When a task moves into another state the previous state is
  236. forgotten about, but some transitions can be deducted, e.g. if a task is now
  237. in the :state:`FAILED` state, it's implied that it was at some point in the
  238. :state:`STARTED` state.
  239. There are also sets of states, like the set of
  240. :state:`failure states <FAILURE_STATES>`, and the set of
  241. :state:`ready states <READY_STATES>`.
  242. The client uses the membership of these sets to decide whether
  243. the exception should be re-raised (:state:`PROPAGATE_STATES`), or if the result can
  244. be cached (which it can if the state is ready).
  245. .. _task-builtin-states:
  246. Built-in States
  247. ---------------
  248. .. state:: PENDING
  249. PENDING
  250. ~~~~~~~
  251. Task is waiting for execution or unknown.
  252. Any task id that is not know is implied to be in the pending state.
  253. .. state:: STARTED
  254. STARTED
  255. ~~~~~~~
  256. Task has been started.
  257. Not reported by default, to enable please see :ref:`task-track-started`.
  258. :metadata: ``pid`` and ``hostname`` of the worker process executing
  259. the task.
  260. .. state:: SUCCESS
  261. SUCCESS
  262. ~~~~~~~
  263. Task has been successfully executed.
  264. :metadata: ``result`` contains the return value of the task.
  265. :propagates: Yes
  266. :ready: Yes
  267. .. state:: FAILURE
  268. FAILURE
  269. ~~~~~~~
  270. Task execution resulted in failure.
  271. :metadata: ``result`` contains the exception occured, and ``traceback``
  272. contains the backtrace of the stack at the point when the
  273. exception was raised.
  274. :propagates: Yes
  275. .. state:: RETRY
  276. RETRY
  277. ~~~~~
  278. Task is being retried.
  279. :metadata: ``result`` contains the exception that caused the retry,
  280. and ``traceback`` contains the backtrace of the stack at the point
  281. when the exceptions was raised.
  282. :propagates: No
  283. .. state:: REVOKED
  284. REVOKED
  285. ~~~~~~~
  286. Task has been revoked.
  287. :propagates: Yes
  288. .. _task-how-they-work:
  289. How it works
  290. ============
  291. Here comes the technical details, this part isn't something you need to know,
  292. but you may be interested.
  293. All defined tasks are listed in a registry. The registry contains
  294. a list of task names and their task classes. You can investigate this registry
  295. yourself:
  296. .. code-block:: python
  297. >>> from celery import registry
  298. >>> from celery import task
  299. >>> registry.tasks
  300. {'celery.delete_expired_task_meta':
  301. <PeriodicTask: celery.delete_expired_task_meta (periodic)>,
  302. 'celery.task.http.HttpDispatchTask':
  303. <Task: celery.task.http.HttpDispatchTask (regular)>,
  304. 'celery.execute_remote':
  305. <Task: celery.execute_remote (regular)>,
  306. 'celery.map_async':
  307. <Task: celery.map_async (regular)>,
  308. 'celery.ping':
  309. <Task: celery.ping (regular)>}
  310. This is the list of tasks built-in to celery. Note that we had to import
  311. ``celery.task`` first for these to show up. This is because the tasks will
  312. only be registered when the module they are defined in is imported.
  313. The default loader imports any modules listed in the
  314. :setting:`CELERY_IMPORTS` setting.
  315. The entity responsible for registering your task in the registry is a
  316. meta class, :class:`~celery.task.base.TaskType`. This is the default
  317. meta class for :class:`~celery.task.base.Task`. If you want to register
  318. your task manually you can set the :attr:`~celery.task.base.Task.abstract`
  319. attribute:
  320. .. code-block:: python
  321. class MyTask(Task):
  322. abstract = True
  323. This way the task won't be registered, but any task subclassing it will.
  324. When tasks are sent, we don't send the function code, just the name
  325. of the task. When the worker receives the message it can just look it up in
  326. the task registry to find the execution code.
  327. This means that your workers should always be updated with the same software
  328. as the client. This is a drawback, but the alternative is a technical
  329. challenge that has yet to be solved.
  330. .. _task-best-practices:
  331. Tips and Best Practices
  332. =======================
  333. .. _task-ignore_results:
  334. Ignore results you don't want
  335. -----------------------------
  336. If you don't care about the results of a task, be sure to set the
  337. :attr:`~celery.task.base.Task.ignore_result` option, as storing results
  338. wastes time and resources.
  339. .. code-block:: python
  340. @task(ignore_result=True)
  341. def mytask(...)
  342. something()
  343. Results can even be disabled globally using the
  344. :setting:`CELERY_IGNORE_RESULT` setting.
  345. .. _task-disable-rate-limits:
  346. Disable rate limits if they're not used
  347. ---------------------------------------
  348. Disabling rate limits altogether is recommended if you don't have
  349. any tasks using them. This is because the rate limit subsystem introduces
  350. quite a lot of complexity.
  351. Set the :setting:`CELERY_DISABLE_RATE_LIMITS` setting to globally disable
  352. rate limits:
  353. .. code-block:: python
  354. CELERY_DISABLE_RATE_LIMITS = True
  355. .. _task-synchronous-subtasks:
  356. Avoid launching synchronous subtasks
  357. ------------------------------------
  358. Having a task wait for the result of another task is really inefficient,
  359. and may even cause a deadlock if the worker pool is exhausted.
  360. Make your design asynchronous instead, for example by using *callbacks*.
  361. Bad:
  362. .. code-block:: python
  363. @task()
  364. def update_page_info(url):
  365. page = fetch_page.delay(url).get()
  366. info = parse_page.delay(url, page).get()
  367. store_page_info.delay(url, info)
  368. @task()
  369. def fetch_page(url):
  370. return myhttplib.get(url)
  371. @task()
  372. def parse_page(url, page):
  373. return myparser.parse_document(page)
  374. @task()
  375. def store_page_info(url, info):
  376. return PageInfo.objects.create(url, info)
  377. Good:
  378. .. code-block:: python
  379. @task(ignore_result=True)
  380. def update_page_info(url):
  381. # fetch_page -> parse_page -> store_page
  382. fetch_page.delay(url, callback=subtask(parse_page,
  383. callback=subtask(store_page_info)))
  384. @task(ignore_result=True)
  385. def fetch_page(url, callback=None):
  386. page = myhttplib.get(url)
  387. if callback:
  388. # The callback may have been serialized with JSON,
  389. # so best practice is to convert the subtask dict back
  390. # into a subtask object.
  391. subtask(callback).delay(url, page)
  392. @task(ignore_result=True)
  393. def parse_page(url, page, callback=None):
  394. info = myparser.parse_document(page)
  395. if callback:
  396. subtask(callback).delay(url, info)
  397. @task(ignore_result=True)
  398. def store_page_info(url, info):
  399. PageInfo.objects.create(url, info)
  400. We use :class:`~celery.task.sets.subtask` here to safely pass
  401. around the callback task. :class:`~celery.task.sets.subtask` is a
  402. subclass of dict used to wrap the arguments and execution options
  403. for a single task invocation.
  404. .. seealso::
  405. :ref:`sets-subtasks` for more information about subtasks.
  406. .. _task-performance-and-strategies:
  407. Performance and Strategies
  408. ==========================
  409. .. _task-granularity:
  410. Granularity
  411. -----------
  412. The task granularity is the amount of computation needed by each subtask.
  413. It's generally better to split your problem up in many small tasks, than
  414. having a few long running ones.
  415. With smaller tasks you can process more tasks in parallel and the tasks
  416. won't run long enough to block the worker from processing other waiting tasks.
  417. However, executing a task does have overhead. A message needs to be sent, data
  418. may not be local, etc. So if the tasks are too fine-grained the additional
  419. overhead may not be worth it in the end.
  420. .. seealso::
  421. The book `Art of Concurrency`_ has a whole section dedicated to the topic
  422. of task granularity.
  423. .. _`Art of Concurrency`: http://oreilly.com/catalog/9780596521547
  424. .. _task-data-locality:
  425. Data locality
  426. -------------
  427. The worker processing the task should be as close to the data as
  428. possible. The best would be to have a copy in memory, the worst being a
  429. full transfer from another continent.
  430. If the data is far away, you could try to run another worker at location, or
  431. if that's not possible, cache often used data, or preload data you know
  432. is going to be used.
  433. The easiest way to share data between workers is to use a distributed caching
  434. system, like `memcached`_.
  435. .. seealso::
  436. The paper `Distributed Computing Economics`_ by Jim Gray is an excellent
  437. introduction to the topic of data locality.
  438. .. _`Distributed Computing Economics`:
  439. http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
  440. .. _`memcached`: http://memcached.org/
  441. .. _task-state:
  442. State
  443. -----
  444. Since celery is a distributed system, you can't know in which process, or even
  445. on what machine the task will run. Indeed you can't even know if the task will
  446. run in a timely manner, so please be wary of the state you pass on to tasks.
  447. One gotcha is Django model objects. They shouldn't be passed on as arguments
  448. to task classes, it's almost always better to re-fetch the object from the
  449. database instead, as there are possible race conditions involved.
  450. Imagine the following scenario where you have an article and a task
  451. that automatically expands some abbreviations in it.
  452. .. code-block:: python
  453. class Article(models.Model):
  454. title = models.CharField()
  455. body = models.TextField()
  456. @task
  457. def expand_abbreviations(article):
  458. article.body.replace("MyCorp", "My Corporation")
  459. article.save()
  460. First, an author creates an article and saves it, then the author
  461. clicks on a button that initiates the abbreviation task.
  462. >>> article = Article.objects.get(id=102)
  463. >>> expand_abbreviations.delay(model_object)
  464. Now, the queue is very busy, so the task won't be run for another 2 minutes,
  465. in the meantime another author makes some changes to the article,
  466. when the task is finally run, the body of the article is reverted to the old
  467. version, because the task had the old body in its argument.
  468. Fixing the race condition is easy, just use the article id instead, and
  469. re-fetch the article in the task body:
  470. .. code-block:: python
  471. @task
  472. def expand_abbreviations(article_id):
  473. article = Article.objects.get(id=article_id)
  474. article.body.replace("MyCorp", "My Corporation")
  475. article.save()
  476. >>> expand_abbreviations(article_id)
  477. There might even be performance benefits to this approach, as sending large
  478. messages may be expensive.
  479. .. _task-database-transactions:
  480. Database transactions
  481. ---------------------
  482. Let's look at another example:
  483. .. code-block:: python
  484. from django.db import transaction
  485. @transaction.commit_on_success
  486. def create_article(request):
  487. article = Article.objects.create(....)
  488. expand_abbreviations.delay(article.pk)
  489. This is a Django view creating an article object in the database,
  490. then passing its primary key to a task. It uses the `commit_on_success`
  491. decorator, which will commit the transaction when the view returns, or
  492. roll back if the view raises an exception.
  493. There is a race condition if the task starts executing
  494. before the transaction has been committed: the database object does not exist
  495. yet!
  496. The solution is to **always commit transactions before applying tasks
  497. that depends on state from the current transaction**:
  498. .. code-block:: python
  499. @transaction.commit_manually
  500. def create_article(request):
  501. try:
  502. article = Article.objects.create(...)
  503. except:
  504. transaction.rollback()
  505. raise
  506. else:
  507. transaction.commit()
  508. expand_abbreviations.delay(article.pk)
  509. .. _task-example:
  510. Example
  511. =======
  512. Let's take a real wold example; A blog where comments posted needs to be
  513. filtered for spam. When the comment is created, the spam filter runs in the
  514. background, so the user doesn't have to wait for it to finish.
  515. We have a Django blog application allowing comments
  516. on blog posts. We'll describe parts of the models/views and tasks for this
  517. application.
  518. blog/models.py
  519. --------------
  520. The comment model looks like this:
  521. .. code-block:: python
  522. from django.db import models
  523. from django.utils.translation import ugettext_lazy as _
  524. class Comment(models.Model):
  525. name = models.CharField(_("name"), max_length=64)
  526. email_address = models.EmailField(_("e-mail address"))
  527. homepage = models.URLField(_("home page"),
  528. blank=True, verify_exists=False)
  529. comment = models.TextField(_("comment"))
  530. pub_date = models.DateTimeField(_("Published date"),
  531. editable=False, auto_add_now=True)
  532. is_spam = models.BooleanField(_("spam?"),
  533. default=False, editable=False)
  534. class Meta:
  535. verbose_name = _("comment")
  536. verbose_name_plural = _("comments")
  537. In the view where the comment is posted, we first write the comment
  538. to the database, then we launch the spam filter task in the background.
  539. .. _task-example-blog-views:
  540. blog/views.py
  541. -------------
  542. .. code-block:: python
  543. from django import forms
  544. from django.http import HttpResponseRedirect
  545. from django.template.context import RequestContext
  546. from django.shortcuts import get_object_or_404, render_to_response
  547. from blog import tasks
  548. from blog.models import Comment
  549. class CommentForm(forms.ModelForm):
  550. class Meta:
  551. model = Comment
  552. def add_comment(request, slug, template_name="comments/create.html"):
  553. post = get_object_or_404(Entry, slug=slug)
  554. remote_addr = request.META.get("REMOTE_ADDR")
  555. if request.method == "post":
  556. form = CommentForm(request.POST, request.FILES)
  557. if form.is_valid():
  558. comment = form.save()
  559. # Check spam asynchronously.
  560. tasks.spam_filter.delay(comment_id=comment.id,
  561. remote_addr=remote_addr)
  562. return HttpResponseRedirect(post.get_absolute_url())
  563. else:
  564. form = CommentForm()
  565. context = RequestContext(request, {"form": form})
  566. return render_to_response(template_name, context_instance=context)
  567. To filter spam in comments we use `Akismet`_, the service
  568. used to filter spam in comments posted to the free weblog platform
  569. `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
  570. need to pay. You have to sign up to their service to get an API key.
  571. To make API calls to `Akismet`_ we use the `akismet.py`_ library written by
  572. Michael Foord.
  573. .. _task-example-blog-tasks:
  574. blog/tasks.py
  575. -------------
  576. .. code-block:: python
  577. from akismet import Akismet
  578. from celery.decorators import task
  579. from django.core.exceptions import ImproperlyConfigured
  580. from django.contrib.sites.models import Site
  581. from blog.models import Comment
  582. @task
  583. def spam_filter(comment_id, remote_addr=None, **kwargs):
  584. logger = spam_filter.get_logger(**kwargs)
  585. logger.info("Running spam filter for comment %s" % comment_id)
  586. comment = Comment.objects.get(pk=comment_id)
  587. current_domain = Site.objects.get_current().domain
  588. akismet = Akismet(settings.AKISMET_KEY, "http://%s" % domain)
  589. if not akismet.verify_key():
  590. raise ImproperlyConfigured("Invalid AKISMET_KEY")
  591. is_spam = akismet.comment_check(user_ip=remote_addr,
  592. comment_content=comment.comment,
  593. comment_author=comment.name,
  594. comment_author_email=comment.email_address)
  595. if is_spam:
  596. comment.is_spam = True
  597. comment.save()
  598. return is_spam
  599. .. _`Akismet`: http://akismet.com/faq/
  600. .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py