Skip to content

Instantly share code, notes, and snippets.

@jmcclell
Created December 14, 2011 16:57
Show Gist options
  • Save jmcclell/1477428 to your computer and use it in GitHub Desktop.
Save jmcclell/1477428 to your computer and use it in GitHub Desktop.
Django template tag for retrieving Stackoverflow reputation score via Py-StackExchange
'''
Template tag for returning Stackoverflow reputation
Requires Py-StackExchange (https://github.com/lucjon/Py-StackExchange/)
This isn't really meant to be consumed as-is for the following reasons:
1. Built in logic for caching isn't ideal for making this distributable
2. Having a template tag reach out to a 3rd party server could cause
performance issues when rendering a template if the 3rd party server 404s
3. This isn't tested very well
4. I'm new to Python/Django
Enjoy!
Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
'''
import logging
from django.core.cache import cache
from django import template
from stackauth import StackAuth
from stackexchange import Site, StackOverflow
from DevPortfolio.util import is_numeric
logger = logging.getLogger(__name__)
def get_stackoverflow_rep(user_id):
reputation = cache.get('so_rep');
if (reputation == None):
stack_auth = StackAuth()
so = Site(StackOverflow, cache=0)
accounts = stack_auth.api_associated(so, user_id)
for account in accounts:
if (account.on_site.name == 'Stack Overflow'):
reputation = account.reputation
cache.set('so_rep', reputation)
if (reputation == None):
reputation = 0;
return reputation
class StackOverflowRepNode(template.Node):
def __init__(self, user_id):
self.user_id = user_id
def render(self, context):
return get_stackoverflow_rep(self.user_id)
def do_stackoverflow_rep(parser, token):
try:
tag_name, user_id = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires a single argument" % token.contents.split()[0])
if not is_numeric(user_id):
raise template.TemplateSyntaxError("%r requires a numeric argument" % tag_name)
return StackOverflowRepNode(user_id)
register = template.Library()
register.tag('stackoverflow_rep', do_stackoverflow_rep)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment