通过外部网站上传图片到gravatar个人资料

时间:2011-01-23 10:58:03

标签: python django gravatar

我想知道是否可以创建上传功能,通过我自己的网站将图片上传到gravatar网站?

2 个答案:

答案 0 :(得分:3)

是的,这是可能的。请参阅http://en.gravatar.com/site/implement/xmlrpc/,特别是grav.saveData或grav.SaveUrl调用。

答案 1 :(得分:2)

是的,可能!

import base64

from xmlrpclib import ServerProxy, Fault
from hashlib import md5


class GravatarXMLRPC(object):
    API_URI = 'https://secure.gravatar.com/xmlrpc?user={0}'

    def __init__(self, request, password=''):
        self.request = request
        self.password = password
        self.email = sanitize_email(request.user.email)
        self.email_hash = md5_hash(self.email)
        self._server = ServerProxy(
            self.API_URI.format(self.email_hash))

    def saveData(self, image):
        """ Save binary image data as a userimage for this account """           
        params = { 'data': base64_encode(image.read()), 'rating': 0, }
        return self._call('saveData', params)
        #return self.useUserimage(image)

    def _call(self, method, params={}):
        """ Call a method from the API, gets 'grav.' prepended to it. """
        args = { 'password': self.password, }
        args.update(params)

        try:
            return getattr(self._server, 'grav.' + method, None)(args)
        except Fault as error:
            error_msg = "Server error: {1} (error code: {0})"
            print error_msg.format(error.faultCode, error.faultString)


def base64_encode(obj):
    return base64.b64encode(obj)

def sanitize_email(email):
    return email.lower().strip()

def md5_hash(string):
    return md5(string.encode('utf-8')).hexdigest()

只需在您的视图中调用该类:)