需要为Python独立的py应用程序获取用于Google Drive的OAuth'flow'流程

时间:2013-05-29 09:31:06

标签: python oauth-2.0 google-drive-api credentials

我需要为GoogDRIVE工作获得OAuth2'流程'。

以前我已经获得了成功令牌的功能,但是我需要设置它,所以我不需要每次都获取令牌,只需一次就可以了。

以下是我所处的位置,基于:https://developers.google.com/api-client-library/python/guide/aaa_oauth

import httplib2
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
from apiclient.discovery import build

flow = OAuth2WebServerFlow(client_id='107......539.apps.googleusercontent.com',
                       client_secret='dVvq2itsasecretbxzG',
                       scope='https://www.googleapis.com/auth/drive',
                       redirect_uri='urn:ietf:wg:oauth:2.0:oob')

#retrieve if available
storage = Storage('OAuthcredentials.txt')
credentials = storage.get()

if  credentials is None:
    #step 1
    auth_uri = flow.step1_get_authorize_url() # Redirect the user to auth_uri
    print 'Go to the following link in your browser: ' + auth_uri
    code = raw_input('Enter verification code: ').strip()
else:
    code = credentials #yeah i know this bit is wrong, but pls send HELP!

#step 2
credentials = flow.step2_exchange(code)

#authorise 
http = httplib2.Http()
http = credentials.authorize(http)
print 'authorisation completed'

#build
service = build('drive', 'v2', http=http)

#store for next time
storage.put(credentials)

它是一个独立的应用程序。所以我首先要以正确的方式解决这个问题吗? 如果是,如何在code else中输入{{1}}凭据?

1 个答案:

答案 0 :(得分:2)

是的,这是一个简单的错误。以下是替换上述Q中的位的工作片段:

......
if  credentials is None:
    #step 1
    auth_uri = flow.step1_get_authorize_url() # Redirect the user to auth_uri
    print 'Go to the following link in your browser: ' + auth_uri
    code = raw_input('Enter verification code: ').strip()
    #step 2
    credentials = flow.step2_exchange(code)
else:
    print 'GDrive credentials are still current'

#authorise
http = httplib2.Http()
http = credentials.authorize(http)
print 'Authorisation successfully completed'
......etc

欢呼声