Python/GCP 健全性检查:这是在 POST 调用中引用存储在 GCP 存储中的图像的正确方法吗?



>场景:存储在 GCP 存储桶中的图像文件需要通过 POST 发送到第三方 REST 端点

问题:这真的是最好的模式吗?有没有更有效、更不冗长的方法?

我们有图片由移动应用程序上传到 GCP 存储桶。当图像上传的 finalize 事件触发时,我们有一个 GCP 云函数 (Python 3(,它通过获取上传图像的 ref 来对此做出反应,将其下载到临时文件,然后使用该临时文件作为 POST 的图像源。这是我们当前的代码,它可以工作,但在我看来,多个open命令似乎令人费解。更具体地说:是否有更好的方法可以简单地从 GCP 存储获取图像 blob 并将其附加到 POST 调用,而无需先将其另存为本地文件,然后打开它以便可以附加到 POST?

def third_party_upload(data, context):
# get image from bucket
storage_client = storage.Client()
bucket = storage_client.bucket(data['bucket'])
image_blob = bucket.get_blob(data['name'])
download_path = '/tmp/{}.jpg'.format(str(uuid.uuid4())) #temp image file download location
# save GCP Storage blob as a temp file
with open(download_path, 'wb') as file_obj:
image_blob.download_to_file(file_obj)
# open temp file and send to 3rd-party via rest post call
with open(download_path, 'rb') as img:
files = {'image': (data['name'], img, 'multipart/form-data', {'Expires': '0'}) }
headers = {
'X-Auth-Token': api_key,
'Content-Type': 'image/jpg',
'Accept': 'application/json'
}
# make POST call
response = requests.post(third_party_endpoint, headers=headers, files=files)
print('POST response:', response)

更新:一些评论者提到签名URL是一种可能性,我同意它们是一个很好的选择。但是,我们坚持要求将图像二进制文件作为 POST 正文包含在内。在这种情况下,签名 URL 将不起作用。

HTTP 方法 POST 需要数据。您必须在 HTTP 请求中提供该数据。除了读取云存储数据之外,没有神奇的方法可以获取它。该过程是从云存储读取数据,然后将该数据提供给 POST 请求。

如果您能够将 URL 发送到第三方终端节点而不是实际图像内容,则可以使用 签名 URL 提供对图像的限时访问,而无需提供对存储桶的第三方访问权限或将存储桶公开。

更多信息请点击此处:https://cloud.google.com/storage/docs/access-control/signed-urls

最新更新