简体   繁体   English

使用api从谷歌云存储下载文件

[英]download a file from google cloud storage with the api

I currently use gsutil cp to download files from my bucket but that requires you to have a bunch of stuff installed. 我目前使用gsutil cp从我的存储桶下载文件,但这需要你安装一堆东西。

I just want to download it using a simple API request like: 我只想使用简单的API请求下载它,例如:

http://storage.googleapis.com/mybucket/pulltest/pulltest.csv

This gives me access denied. 这让我拒绝访问。 How are the auth parameters formatted to bypass this? 如何格式化auth参数来绕过这个?

If your object can be downloaded by an anonymous user, you can download an object exactly like that. 如果您的对象可以由匿名用户下载,则可以下载与此完全相同的对象。

Doing OAuth by hand is tricky, though. 但是,手工操作OAuth很棘手。 The thing you'll need to present to Google is an access token. 您需要向Google呈现的内容是访问令牌。 The auth header looks like this: auth标头如下所示:

# This has gotta be in an HTTPS request. No sending credentials over HTTP, please.
Authorization: Bearer something.abcdabcdabcdabcdabcdabcdabcdabcd

Getting an access token requires an OAuth exchange, which is a bit tricky. 获取访问令牌需要进行OAuth交换,这有点棘手。 There's an online playground that will take care of it for you: https://developers.google.com/oauthplayground/ 有一个在线游乐场可以为您处理: https//developers.google.com/oauthplayground/

There's also a bunch of documentation on the exact details, although you likely won't want to do it by hand: https://developers.google.com/identity/protocols/OAuth2 还有一些关于确切细节的文档,尽管您可能不想手动执行: https//developers.google.com/identity/protocols/OAuth2

Access tokens are only good for a few minutes. 访问令牌只有几分钟。 They're not meant to be persisted. 它们并不意味着坚持下去。 If you're going to be doing this a lot, you may want to install the gcloud SDK, which has a " print-access-token " command that is very useful. 如果你要做很多事情,你可能想要安装gcloud SDK,它有一个非常有用的“ print-access-token ”命令。

Figured out how to do what I wanted: 弄清楚如何做我想要的:

from google.cloud.storage.client import Client
from google.cloud.storage.bucket import Bucket
from google.cloud.storage.blob import Blob
from google.oauth2.service_account import Credentials

credentials = Credentials.from_service_account_file('key.json')
client = Client(project='project', credentials=credentials)
bucket = Bucket(client=client, name='bucket')
blob = Blob(name='pulltest/pulltest.csv', bucket=bucket)

print blob.exists()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM