我使用django作为我的web框架,
我发现python-social-auth对于OAuth来说是一个很好的方案
我还希望从谷歌OAuth2访问谷歌驱动器
我在Google Drive SDK上看到了一些示例代码:
from apiclient.discovery import build
def build_service(credentials):
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http=http)
所以,看起来我需要获取凭证来实例化服务器对象 我该如何做才能获得凭据? 或者我该怎么做才能使用谷歌驱动器?
答案 0 :(得分:1)
我遇到了同样的情况,我一直在看oauth2client是如何工作的,所以我从使用python-social-auth认证获得的数据中生成了凭证,I当用户第一次登录网站时,将此逻辑放在管道中。如下:
import datetime
from django.conf import settings
from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI
from oauth2client.client import OAuth2Credentials, _extract_id_token
from oauth2client.django_orm import Storage
from website.models import CredentialsModel
def set_google_credentials(strategy, details, response, user=None, *args, **kwargs):
if user and kwargs.get('is_new'):
token_expiry = datetime.datetime.utcnow() + datetime.timedelta(seconds=int(response.get('expires_in')))
id_token = _extract_id_token(response.get('id_token'))
credential = OAuth2Credentials(
access_token=response.get('access_token'),
client_id=settings.SOCIAL_AUTH_GOOGLE_PLUS_KEY,
client_secret=settings.SOCIAL_AUTH_GOOGLE_PLUS_SECRET,
refresh_token=response.get('refresh_token'),
token_expiry=token_expiry,
token_uri=GOOGLE_TOKEN_URI,
user_agent=None,
revoke_uri=GOOGLE_REVOKE_URI,
id_token=id_token,
token_response=response)
storage = Storage(CredentialsModel, 'id', user, 'credential')
storage.put(credential)
然后在我的设置中:
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.social_user',
'social.pipeline.user.get_username',
'social.pipeline.user.create_user',
'myapp.pipeline.set_google_credentials'
# more pipelines
)
然后当我需要用户凭据时:
更新:由于@bcoover注意到Storage
得到的结果需要解码和删除。
user = # get a user instance, from the request for example
storage = Storage(CredentialsModel, 'id', user, 'credential')
import pickle, base64
credentials = (pickle.loads(base64.b64decode(storage.get())))
# do what ever you want with the credentials
这种方法目前适用于我,但如果有人有更好的方法,我会感激不尽。 Storage和CredentialsModel来自https://developers.google.com/api-client-library/python/guide/django
答案 1 :(得分:1)
这非常有帮助,谢谢@eyscode! 我遇到了与@areyoueye相同的问题,结果看到谷歌代码后,结果需要解码和去除,然后效果很好! 这是修改后的代码:
import pickle
...
storage = Storage(GoogleCredential, 'id', user, 'credential')
credentials = (pickle.loads(base64.b64decode(storage.get())))
...
然后执行print(),你应该得到一个像这样的输出对象:
...
print(credentials)
<oauth2client.client.OAuth2Credentials object at 0x7fa2837af630>