使用源码包安装
a). 安装gdata.py。下载gdata.py压缩包,然后按照如下方法安装
sudo python setup.py install
or
python setup.py install --home=~
and set your PYTHONPATH to include your home directory.
b). 下载 douban-python源码包并解压
c). 按照如下命令安装douban-python
sudo python setup.py install
安装好之后将douban-python中的douban放到apps里面作为app使用。
def douban_client(request):
DOUBAN_API_KEY = ''
DOUBAN_API_SECRET = ''
client = OAuthClient(key=DOUBAN_API_KEY, secret=DOUBAN_API_SECRET)
return client
@csrf_exempt
def douban_authorize(request):
CALLBACK_URL = "http://localhost:8000/douban_login"
client = douban_client(request)
request_tokens = {}
key, secret = client.get_request_token()
request.session['key'] = key
request.session['secret'] = secret
request.session['user_id'] = request.GET['user_id']
if key and secret:
request_tokens[key] = secret
url = client.get_authorization_url(key, secret, callback=CALLBACK_URL)
return HttpResponseRedirect(url) //这里将调用douban_login方法,在urls.py中配置
@csrf_exempt
def douban_login(request):
client = douban_client(request)
user_id = request.session['user_id']
access_token, access_secret, douban_uid = client.get_access_token(request.session['key'], request.session['secret'])
try:
profile = UserProfile.objects.get(user=user_id)
douban_service = DoubanService(api_key=access_token, secret=access_secret)
data = urllib.urlopen("http://api.douban.com/people/" + str(douban_uid)).read()
doc = xml.dom.minidom.parseString(data)
title = doc.getElementsByTagName("title")
avatar = doc.getElementsByTagName("link")
profile.avatar_url = avatar[2].getAttribute("href")
profile.save()
profile.user.first_name = title[0].childNodes[0].nodeValue
profile.user.save()
return JsonResponse(success({}))
except ObjectDoesNotExist:
return JsonResponse(fail({}))
具体详细的授权方式可查看豆瓣开发者的API,现在都推出OAuth2.0,个人感觉微博的授权比较方便,但是python的版本也有BUG。