如何授权访问GCS的请求?

时间:2014-03-20 08:05:45

标签: python google-cloud-storage

我的Python代码需要访问GCS中的文件,我仍然坚持认证。

我阅读了https://developers.google.com/api-client-library/python/guide/aaa_oauth并为auth添加了以下代码:

flow = OAuth2WebServerFlow( client_id='995.apps.googleusercontent.com',
                            client_secret='Zcxxxxxxxx',
                            scope='https://www.googleapis.com/auth/devstorage.read_only',
                            redirect_uri='urn:ietf:wg:oauth:2.0:oob')

auth_uri = flow.step1_get_authorize_url()

credentials = flow.step2_exchange('3/xxxxxxxxxxxxx') # I copy the code returned in
                                                     # browser after opening the
                                                     # URL of auth_uri

http = httplib2.Http()
http = credentials.authorize(http)

client = discovery.build('storage', 'v1beta2', http=http)

request = client.objects().list(
    bucket = 'mybucket',
    prefix = 'myfolder/sub-folder',
    key =   'xxxxxx_2Ks') # my API key

我知道代码应该是不正确的,因为无法打开浏览器来获取代码并在Python程序中手动返回。

我希望我的代码可以获取客户端ID,客户端密码,范围和重定向,然后可以创建可以长时间使用的授权请求,是否可能?

有人可以提供建议并提供简单的示例代码吗?谢谢你的帮助!

===================================

03/21更新:

我刚刚尝试了下面的代码并想让我的代码至少通过一次..

auth_uri = flow.step1_get_authorize_url()
webbrowser.open(auth_uri)
mycode = input("Please input the code: ")

credentials = flow.step2_exchange(mycode)

http = httplib2.Http()
http = credentials.authorize(http)

client = discovery.build('storage', 'v1beta2', http=http)

request = client.objects().list(.....)

当我尝试使用该请求时,却得到 oauth2client.client.FlowExchangeError:invalid_request

1 个答案:

答案 0 :(得分:1)

如果您运行您发布的代码并从浏览器复制/粘贴一次,那么您应该拥有一个有效的凭据对象。为避免在将来的运行中需要使用浏览器,您可以像这样保存刷新令牌:

# Save refresh token (to file or elsewhere)
with open('refresh_token_file', 'w') as token_file:
  token_file.write(credentials.refresh_token)

然后,稍后,您可以加载您保存的刷新令牌(不与浏览器进行任何交互),并将该令牌与新的httplib2.Http关联:

# Load refresh token from file (or wherever it's stored) into saved_refresh_token)
# ...

credentials = OAuth2Credentials(None, your_client_id, your_client_secret, saved_refresh_token, None, 'https://accounts.google.com/o/oauth2/token', None)
credentials.refresh(http)

确保您选择保存令牌的位置是安全的。只有您和有权作为您的人才能访问它。