![](/img/trans.png)
[英]Is it possible to use x-goog-if-generation-match in google.cloud.storage python client?
[英]google.cloud.storage allows access but gcsfs does not
我想使用gcsfs
连接到谷歌云存储上的一个桶。 到目前为止,我一直只使用原生的google.cloud
模块,但事实证明我实际上需要某个应用程序的对象之类的文件,所以不得不切换。
我的GOOGLE_APPLICATION_CREDENTIALS
环境变量指向本地文件系统上的 JSON 文件。 使用google.cloud
,我可以毫无问题地访问云存储中的存储桶。 但是我没有使用gcsfs
。 下面是一些代码来说明我的意思:
from google.cloud import storage
import gcsfs
import google.auth
storage_client = storage.Client()
bucket = storage_client.bucket(...)
blob = bucket.blob(f'data/audio_wav/test.wav')
bts = blob.download_as_bytes()
credentials, _ = google.auth.default()
fs = gcsfs.GCSFileSystem(project=..., token=credentials)
folders = fs.ls('data') #throws error
正如所评论的,最后一行抛出似乎是身份验证错误的内容:
google.auth.exceptions.RefreshError: ('invalid_scope: Invalid_scope: Invalid OAuth scope or ID token audience provided.', {'error': 'invalid_scope', 'error_description': 'Invalid OAuth scope or ID token audience provided.'})
我认为如果google.cloud.storage
接受我的凭据,那么gcsfs
也应该如此。 为什么会出现上述错误,我该如何解决?
或者,有没有办法使用google.cloud.storage
而不是gcsfs
打开像 object 这样的文件?
{
"type": "service_account",
"project_id": ...,
"private_key_id": ....,
"private_key": ...,
"client_email": "ai-dj-884@ai-dj-76527.iam.gserviceaccount.com",
"client_id": "113487991001810308893",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/ai-dj-884%40ai-dj-76527.iam.gserviceaccount.com"
}
正如@John Hanley 在评论中建议的那样,将身份验证模式(即“token”)从“token=credentials”修改为“token=None”,以使用您的默认 gcloud 凭据或尝试从 Google 元数据服务获取凭据,或回退到匿名访问。
有关详细信息,请参阅凭据。
要使用“google.cloud.storage”而不是“gcsfs”打开文件,您可以使用以下方法,
#create storage client
storage_client = storage.Client('json-file-path’')
#get bucket with name
bucket = storage_client.get_bucket('bucket-name')
#get bucket data as blob
blob = bucket.get_blob('file-name’)
错误与您的凭据 scope 有关。
正如@John Hanley 提到的,您可以使用“googleapis.com/auth/cloud-platform”scope,这不会给您任何 scope 错误,但您的权限是唯一阻止服务帐户访问 Google 服务的因素。
下面的代码片段使用 GCS Readonly scope,因此如果您想写回 GCS 将不起作用。
from google.cloud import storage
import gcsfs
import google.auth
credentials = google.auth.default()
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/devstorage.read_only']) # This is what you are missing
fs = gcsfs.GCSFileSystem(project=..., token=scoped_credentials)
folders = fs.ls('data')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.