使用Pydrive身份验证

时间:2014-05-08 12:20:46

标签: python-2.7 google-drive-api google-oauth

我使用gdata模块从google doc访问,上传,下载文件。我有oauth的关键和秘密。现在我想切换到谷歌驱动器API。在google drive api上学习和学习一点,它在身份验证方面看起来有点不同。我也下载了pydrive模块,因此我可以开始了。但我无法授权我的服务器端python代码使用我的oauth密钥授权/验证用户并访问我的驱动器。任何人都有任何有关如何使用pydrive通过我以前的auth键访问我的驱动器的知识。我只需要一种简单的方法来进行身份验证。

1 个答案:

答案 0 :(得分:1)

对于使用gdata模块,我们使用以下任何一种凭证 - 1 GT;用户名和&密码或 2 - ;消费者oauth密钥和密钥。

由于您尝试使用oauth凭据,我认为您需要一个适用于Google云端硬盘的域范围委派访问权限,这将有助于您通过域名将文件上传/下载到任何用户的Google驱动器中。< / p>

为此,您需要从中生成服务帐户类型的新客户端ID Developer's Console

* .p12文件将被下载。记下保存它的路径。   另请注意您的服务帐户的电子邮件地址。这些将在编码时使用。

下面是你必须仔细编辑的python代码 - 收集帐户私人密码的路径,电子邮件:@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

希望这会有所帮助! 资源 - Google Drive API

import httplib2
import pprint
import sys

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

"""Email of the Service Account"""
SERVICE_ACCOUNT_EMAIL = 'something@developer.gserviceaccount.com'

"""Path to the Service Account's Private Key file"""
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'PATH TO SERIVE ACCOUNT PRIVATE KEY'

def createDriveService(user_email):
  """Build and returns a Drive service object authorized with the service accounts
  that act on behalf of the given user.

  Args:
    user_email: The email of the user.
  Returns:
    Drive service object.
  """
  f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
  key = f.read()
  f.close()

  credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
      scope='https://www.googleapis.com/auth/drive', sub=user_email)
  http = httplib2.Http()
  http = credentials.authorize(http)

  return build('drive', 'v2', http=http)

drive_service=createDriveService('EMAIL_ID@YOURDOMAIN.COM')

result = []
page_token = None


while True:
    try:
        param = {}
        if page_token:
            param['pageToken'] = page_token
        files = drive_service.files().list().execute()
        #print files
        result.extend(files['items'])
        page_token = files.get('nextPageToken')
        if not page_token:
            break
    except errors.HttpError, error:
        print 'An error occurred: %s' % error
        break

for f in result:
    print '\n\nFile: ',f.get('title')

    print "\n"