Created
January 16, 2015 19:06
-
-
Save arkanister/e63e321262b436ef0626 to your computer and use it in GitHub Desktop.
Django gravatar url by template filter
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 | |
import hashlib | |
import httplib | |
import urllib | |
from django import template | |
from django.conf import settings | |
register = template.Library() | |
GRAVATAR_DOMAIN = "gravatar.com" | |
GRAVATAR_PATH = "/avatar/" | |
@register.filter(name="show_gravatar_url") | |
def show_gravatar_url(email, size=48): | |
""" Uses to get correct url to gravatar email. """ | |
if not email is None: | |
query = urllib.urlencode({ | |
'gravatar_id': hashlib.md5(email).hexdigest(), | |
'size': str(size), | |
'default': '/' | |
}) | |
full_path = "%s?%s" % (GRAVATAR_PATH, query) | |
# Create connection and test for 302 redirect | |
conn = httplib.HTTPConnection(GRAVATAR_DOMAIN) | |
conn.request('HEAD', full_path) | |
response = conn.getresponse() | |
if not response.status == 302: | |
return "http://%s%s" % (GRAVATAR_DOMAIN, full_path) | |
return "%s%s" % (settings.STATIC_URL, "/images/avatar.png") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment