Permalink
Browse files

Updated readme and cleaned up things

  • Loading branch information...
1 parent 1ea5c6c commit b316405d6bcc411900cbe3ea91ee80c2a56d559e @arthurk committed May 8, 2009
Showing with 119 additions and 108 deletions.
  1. +59 −44 README.markdown
  2. +4 −2 disqus/__init__.py
  3. +1 −1 disqus/management/commands/disqus-dumpdata.py
  4. +55 −61 disqus/management/commands/disqus-export.py
View
@@ -1,86 +1,101 @@
# django-disqus
-**WORK IN PROGRESS!**
+django-disqus helps you to easily integrate DISQUS comments into your website.
## Features
-* Export comments from django.contrib.comments to DISQUS.
-* Dump data from DISQUS in local JSON file.
-* Templatetags
+* Export django.contrib.comments to DISQUS
+* Dump DISQUS into local JSON file
+* Templatetags to ease the integration
## Requirements
- * Django 1.0
+ * Django 1.0.x
## Installation
-1. Add 'disqus' to your INSTALLED\_APPS.
-2. Add "DISQUS\_API\_KEY" and "DISQUS\_WEBSITE\_SHORTNAME" to your settings file. You can [http://disqus.com/api/get_my_key/][get your API key here].
+1. Add `disqus` to your `INSTALLED_APPS` setting.
+2. Add `DISQUS_API_KEY` and `DISQUS_WEBSITE_SHORTNAME` to your settings.
-## Usage
+Refer to the [http://wiki.disqus.net/API](DISQUS API) documentation if you
+don't know how to get your API key.
-### Exporting comments
+You can find the shortname of your site on the DISQUS homepage in the right
+sidebar under "_My Websites_".
-To export comments to disqus:
+Example:
- python manage.py disqus-export
+ # settings.py
+
+ INSTALLED_APPS = (
+ ...
+ 'django.contrib.comments',
+ 'disqus',
+ )
-### Dumping data
+ DISQUS_API_KEY = 'FOOBARFOOBARFOOBARFOOBARFOOBARF'
+ DISQUS_WEBSITE_SHORTNAME = 'foobar'
-To dump the data from disqus:
-
- python manage.py disqus-dumpdata
+## Management Commands
-You can pass the --indent option to specify the indentation of the output:
-
- python manage.py disqus-dumpdata --indent=4
+### disqus-export
+
+The `disqus-export` command exports comments from django.contrib.comments to
+DISQUS.
+
+When exporting comments, make sure you have the domain of your Site set. Also
+the Model to which the comments are associated needs a `get_absolute_url()`
+method which returns the absolute url to the page the comments should
+appear on.
+
+Threaded comments are not supported.
+
+Options:
+
+* __-d/--dry-run__: Does not export any comments, but merely outputs the
+comments which would have been exported
+* __-v/--verbosity__: Output verbosity level; 0=minimal output, 1=normal output
+
+### disqus-dumpdata
+
+The `disqus-dumpdata` command dumps DISQUS comments into a local JSON file.
+
+Options:
+
+* __--indent__: Specifies the indent level to use when pretty-printing output
### Templatetags
#### disqus\_dev
In order to get comments working on a local development server you need to
-include the templatetag in your website's `<head>` tag:
+include this templatetag in your website's `<head>`:
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>fooar</title>
- {% load disqus_tags %}
{% disqus_dev %}
</head>
-It sets `disqus_developer` to `1` and `disqus_url` to the current site's
-url if the `DEBUG` setting of your project is set to `True`.
+If the `DEBUG` setting is set to `True` this sets the `disqus_developer`
+variable to `1` to disable url validation. It also sets `disqus_url`
+to the current Site's domain. Without this, it wouldn't be possible to display
+the comment form locally.
#### **disqus\_num\_replies**
-Returns the JavaScript necessary to show the current comment count.
-The JavaScript will replace all permalinks with the `#disqus_thread` anchor
-with the current comment count.
-
- <a href="{{ object.get_absolute_url }}#disqus_thread">View Comments</a>
+Returns the JavaScript necessary to replace all permalinks which have the
+`#disqus_thread` anchor with the comment count for that url.
-Include the templatetag at the bottom of your website before the closing
-`</body>` tag:
+Example:
- {% load disqus_tags %}
+ <a href="{{ object.get_absolute_url }}#disqus_thread">View Comments</a>
{% disqus_num_replies %}
#### **disqus\_show\_comments**
-Include the templatetag in your HTML where you'd like the comments to appear.
-
- {% load disqus_tags %}
- {% disqus_show_comments %}
-
-## Troubleshooting
-
-Make sure that:
+Returns the JavaScript necessary to display the comment form and comments.
-* Each content object has a get\_absolute\_url() method.
-* Your Site has the correct domain set.
-* The content object has a __unicode__ method
+Example:
-## TODO
-
-* `is_usable` for templatetags
+ {% disqus_show_comments %}
View
@@ -1,7 +1,9 @@
import urllib
import urllib2
+from django.core.management.base import CommandError
from django.utils import simplejson as json
+from django.conf import settings
def call(method, data, post=False):
"""
@@ -19,5 +21,5 @@ def call(method, data, post=False):
data = ''
res = json.load(urllib2.urlopen(url, data))
if not res['succeeded']:
- raise CommandError("'%s' failed: %s" % (method, res['code']))
- return res['message']
+ raise CommandError("'%s' failed: %s\nData: %s" % (method, res['code'], data))
+ return res['message']
@@ -35,7 +35,7 @@ def handle(self, *app_labels, **options):
# Get the API key for the forum. Each forum has an unique API key
forum_api_key = call('get_forum_api_key',
{'user_api_key': settings.DISQUS_API_KEY,
- 'forum_id': forum['id']})
+ 'forum_id': data['forum']['id']})
# Get the threads for a forum
data['forum']['threads'] = call('get_thread_list',
@@ -1,11 +1,12 @@
from optparse import make_option
-import urllib
-import urllib2
-
-from django.utils import simplejson as json
+from django.conf import settings
+from django.contrib import comments
+from django.contrib.sites.models import Site, RequestSite
from django.core.management.base import NoArgsCommand
+from django.utils import simplejson as json
+from disqus import call
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
@@ -15,91 +16,84 @@ class Command(NoArgsCommand):
type='choice', choices=['0', '1',],
help='Verbosity level; 0=minimal output, 1=normal output'),
)
- help = 'Export django.contrib.comments to DISQUS'
+ help = 'Export django.contrib.comments to DISQUS'
requires_model_validation = False
- def _call(self, method, data, post=False):
+ def _get_comments_to_export(self):
"""
- Calls `method` from disqus API with data either in POST or GET mode and
- returns deserialized JSON response.
-
- TODO: Check if response was successful
- {'message': None, 'code': 'ok', 'succeeded': True}
-
+ Fetches the comments from the database which should be exported
"""
- url = "%s%s" % ('http://disqus.com/api/', method)
- if post:
- # POST request
- url += "/"
- data = urllib.urlencode(data)
- else:
- # GET request
- url += "?%s" % urllib.urlencode(data)
- data = ''
- return json.loads(urllib2.urlopen(url, data).read())
+ return comments.get_model().objects.order_by('id').filter(is_public=True,
+ is_removed=False)
- def handle(self, **options):
- from django.conf import settings
- from django.contrib.sites.models import Site
- from django.contrib import comments
+ def handle(self, **options):
+ if Site._meta.installed:
+ current_site = Site.objects.get_current()
+ else:
+ current_site = RequestSite(request)
- current_site = Site.objects.get_current()
verbosity = int(options.get('verbosity'))
+ dry_run = int(options.get('verbosity'))
- comments = comments.get_model().objects.order_by('id').filter(is_public__exact=True,
- is_removed__exact=False)
+ comments = self._get_comments_to_export()
comments_count = comments.count()
print "Exporting %d comment(s)" % comments_count
+ if dry_run:
+ print comments
+ return
- if comments_count > 0:
- forums = self._call('get_forum_list', {'user_api_key': settings.DISQUS_API_KEY})
+ if comments_count > 0:
+ # Get a list of all forums for an API key. Each API key can have
+ # multiple forums associated. This application only supports the one
+ # specified under DISQUS_WEBSITE_SHORTNAME
+ forum_list = call('get_forum_list',
+ {'user_api_key': settings.DISQUS_API_KEY})
+ try:
+ forum = [f for f in forum_list if f['shortname'] == settings.DISQUS_WEBSITE_SHORTNAME][0]
+ except IndexError:
+ raise CommandError("Could not find forum. " +
+ "Check your 'DISQUS_WEBSITE_SHORTNAME' setting.")
- for forum in forums['message']:
- if forum['shortname'] == settings.DISQUS_WEBSITE_SHORTNAME:
- forum_id = forum['id']
-
- forum_api_key = self._call('get_forum_api_key',
- {'user_api_key': settings.DISQUS_API_KEY,
- 'forum_id': forum_id})['message']
+ # Get the API key for the forum. Each forum has an unique API key
+ forum_api_key = call('get_forum_api_key',
+ {'user_api_key': settings.DISQUS_API_KEY,
+ 'forum_id': forum['id']})
for comment in comments:
if verbosity >= 1:
print "Exporting comment '%s'" % comment
+ # Construct the url under which the comment should appear
content_obj = comment.content_object
content_obj_url = 'http://%s%s' % (current_site.domain,
content_obj.get_absolute_url())
- #print comment.get_content_object_url()
- thread = self._call('get_thread_by_url', {'forum_api_key': forum_api_key,
- 'url': content_obj_url})['message']
-
- print content_obj.get_allow_comments()
- return
-
- # if no thread was found for the content object's url, create
- # a new one
+ # Try to get the thread by the url, if it doesn't exist we
+ # create a new thread with this url.
+ thread = call('get_thread_by_url', {'forum_api_key': forum_api_key,
+ 'url': content_obj_url})
if not thread:
- # TODO: figure out better identifier for thread
- thread = self._call('thread_by_identifier', {
- 'forum_api_key': forum_api_key,
- 'identifier': content_obj,
- 'title': str(content_obj)}, True)['message']['thread']
+ # create a new thread
+ thread = call('thread_by_identifier', {
+ 'forum_api_key': forum_api_key,
+ 'identifier': content_obj,
+ 'title': str(content_obj)}, True)['thread']
# set the url of the thread
- # TODO: getattr content.obj slug, allow_comments etc.
- self._call('update_thread', {'forum_api_key': forum_api_key,
- 'thread_id': thread['id'],
- 'url': content_obj_url}, True)
+ call('update_thread', {'forum_api_key': forum_api_key,
+ 'thread_id': thread['id'],
+ 'url': content_obj_url}, True)
- # export comment
+
+ # name and email are optional in contrib.comments but required
+ # in DISQUS. If they are not set there will be dummy values
+ # provided
post_data = {'forum_api_key': forum_api_key,
'thread_id': thread['id'],
'message': comment.comment.encode("utf-8"),
- 'author_name': comment.user_name.encode("utf-8"),
- 'author_email': comment.user_email,
+ 'author_name': comment.user_name.encode("utf-8") or 'nobody',
+ 'author_email': comment.user_email or 'nobody@example.org',
'author_url': comment.user_url,
- 'ip_address': comment.ip_address,
'created_at': comment.submit_date.strftime("%Y-%m-%dT%H:%M")}
- self._call('create_post', post_data, True)
+ call('create_post', post_data, True)

0 comments on commit b316405

Please sign in to comment.