刷新令牌Google Drive Api

时间:2014-07-07 18:02:13

标签: oauth-2.0 google-drive-api

我有以下代码获取我的应用程序的访问凭据并将它们存储在一个文件中,这样我就不需要再次登录。但是,访问令牌有效期为1小时,如何使用现有代码的刷新令牌获取有效凭证,而无需用户通过登录和允许应用程序手动执行此操作?

#!/usr/bin/python                                                                                                                         
import httplib2
import pprint

from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage

# Copy your credentials from the console                                                                                                  
CLIENT_ID = 'PASTE_YOUR_ID'
CLIENT_SECRET = 'PASTE_YOUR_SECRET'

# Check https://developers.google.com/drive/scopes for all available scopes                                                               
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'

# Redirect URI for installed apps                                                                                                         
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Create a credential storage object.  You pick the filename.
storage = Storage('a_credentials_file')

# Attempt to load existing credentials.  Null is returned if it fails.
credentials = storage.get()

# Only attempt to get new credentials if the load failed.
if not credentials:

    # Run through the OAuth flow and retrieve credentials                                                                                 
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)

    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    code = raw_input('Enter verification code: ').strip()

    credentials = flow.step2_exchange(code)
    storage.put(credentials)


# Create an httplib2.Http object and authorize it with our credentials                                                                    
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)

# Use 'drive_service' for all of the API calls

0 个答案:

没有答案
相关问题