Created
March 21, 2017 14:13
-
-
Save vitorfs/5188ce0108774dfd19883c369c62fef2 to your computer and use it in GitHub Desktop.
Disqus Python API Latest Comments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
from django.utils.dateparse import parse_datetime | |
from disqusapi import DisqusAPI | |
from .utils import smart_safe_excerpt | |
def get_latest_comments(limit=5): | |
disqus = DisqusAPI(settings.DISQUS_SECRET_KEY, settings.DISQUS_PUBLIC_KEY) | |
forum = 'simpleisbetterthancomplex' | |
results = disqus.get('posts.list', method='get', forum=forum, limit=limit) | |
comments = list() | |
thread_cache = dict() | |
for result in results: | |
thread_id = result['thread'] | |
if thread_id not in thread_cache.keys(): | |
thread = disqus.get('threads.details', method='get', forum=forum, thread=thread_id) | |
thread_cache[thread_id] = { | |
'clean_title': thread['clean_title'], | |
'link': thread['link'] | |
} | |
comments.append({ | |
'id': result['id'], | |
'author_name': result['author']['name'], | |
'author_avatar': result['author']['avatar']['small']['permalink'], | |
'date': parse_datetime(result['createdAt']), | |
'message': smart_safe_excerpt(result['raw_message']), | |
'thread_title': thread_cache[thread_id]['clean_title'], | |
'thread_link': thread_cache[thread_id]['link'] | |
}) | |
return comments |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from __future__ import unicode_literals | |
import bleach | |
def smart_safe_excerpt(value, max_length=100): | |
''' | |
http://stackoverflow.com/questions/5235994/django-template-tag-to-truncate-text | |
''' | |
value = bleach.clean(value, strip=True, tags=list()).strip() | |
if len(value) > max_length: | |
truncd_val = value[:max_length] | |
if not len(value) == max_length + 1 and value[max_length + 1] != ' ': | |
truncd_val = truncd_val[:truncd_val.rfind(' ')] | |
value = u'{}…'.format( | |
bleach.linkify(truncd_val) | |
) | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment