[英]How to properly use create_anonymous_client() function in google cloud storage python library for access on public buckets?
[英]How to create Google Cloud storage access token programmatically python
我需要有一个我在 google 函数中创建的文件的公共 URL。 因此,我想创建一个访问令牌:
我可以使用函数blob.upload_from_string(blob_text)
从 python google 函数上传文件,但我不知道如何为其创建公共 url(或创建访问令牌)。
你能帮我吗?
使用答案进行编辑(几乎从Marc Anthony B的答案中复制粘贴)
blob = bucket.blob(storage_path)
token = uuid4()
metadata = {"firebaseStorageDownloadTokens": token}
blob.metadata = metadata
download_url = 'https://firebasestorage.googleapis.com/v0/b/{}/o/{}?alt=media&token={}' \
.format(bucket.name, storage_path.replace("/", "%2F"), token)
with open(video_file_path, 'rb') as f:
blob.upload_from_file(f)
Firebase Storage for Python 仍然没有自己的 SDK,但您可以改用firebase-admin
。 Firebase Admin SDK 依赖于Google Cloud Storage 客户端库来提供 Cloud Storage 访问权限。 Admin SDK 返回的存储桶引用是在这些库中定义的对象。
将对象上传到 Firebase 存储时,您必须合并自定义访问令牌。 在这种情况下,您可以使用UUID4
。 请参见下面的代码:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
from uuid import uuid4
projectId = '<PROJECT-ID>'
storageBucket = '<BUCKET-NAME>'
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
'projectId': projectId,
'storageBucket': storageBucket
})
bucket = storage.bucket()
# E.g: "upload/file.txt"
bucket_path = "<BUCKET-PATH>"
blob = bucket.blob(bucket_path)
# Create a token from UUID.
# Technically, you can use any string to your token.
# You can assign whatever you want.
token = uuid4()
metadata = {"firebaseStorageDownloadTokens": token}
# Assign the token as metadata
blob.metadata = metadata
blob.upload_from_filename(filename="<FILEPATH>")
# Make the file public (OPTIONAL). To be used for Cloud Storage URL.
blob.make_public()
# Fetches a public URL from GCS.
gcs_storageURL = blob.public_url
# Generates a URL with Access Token from Firebase.
firebase_storageURL = 'https://firebasestorage.googleapis.com/v0/b/{}/o/{}?alt=media&token={}'.format(storageBucket, bucket_path, token)
print({
"gcs_storageURL": gcs_storageURL,
"firebase_storageURL": firebase_storageURL
})
从上面的代码可以看出,我提到了 GCS 和 Firebase URL。 如果您想要来自 GCS 的公共 URL,那么您应该使用make_public()
方法将对象设为公共。 如果您想使用生成的访问令牌,只需将默认 Firebase URL 与所需的变量连接起来。
如果对象已经在 Firebase 存储中并且已经包含访问令牌,那么您可以通过获取对象元数据来获取它。 请参见下面的代码:
# E.g: "upload/file.txt"
bucket_path = "<BUCKET-PATH>"
blob = bucket.get_blob(bucket_path)
# Fetches object metadata
metadata = blob.metadata
# Firebase Access Token
token = metadata['firebaseStorageDownloadTokens']
firebase_storageURL = 'https://firebasestorage.googleapis.com/v0/b/{}/o/{}?alt=media&token={}'.format(storageBucket, bucket_path, token)
print(firebase_storageURL)
有关更多信息,您可以查看此文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.