
本文介绍如何在本地环境中使用 GCS 模拟器,以便在 Cloud Run 上构建使用 Flask 操作 Google Cloud Storage (GCS) 的应用程序。
模拟器选择
fsouza/fake-gcs-server 作为 GCS 模拟器。示例代码及设置
示例代码已上传至 GitHub 仓库(flask-gcs),详细步骤请参考仓库中的 README.md 文件。 通过克隆仓库并运行 make up 命令即可快速搭建本地环境,实现文件的上传、下载和删除操作。
docker-compose.yml 配置
为了在 Flask 容器中使用 GCS 模拟器,需要设置 storage_emulator_host 环境变量:
<code class="yaml">services:
app:
environment:
- storage_emulator_host=http://gcs:4443</code>Flask 中的 Storage Client 配置
通过检查 storage_emulator_host 环境变量来判断是否使用模拟器:
<code class="python">def get_storage_client():
emulator_host = Config.STORAGE_EMULATOR_HOST
if emulator_host:
client = storage.Client(
credentials=AnonymousCredentials(),
project="test",
)
else:
client = storage.Client()
return client</code>总结
在本地开发环境中使用 GCS 模拟器,可以方便地测试 Flask 应用与 GCS 的交互。 生产环境中无需使用模拟器,只需移除 storage_emulator_host 环境变量,指定您的 bucket 名称,并确保 Cloud Run 拥有相应的权限即可。
以上就是创建本地环境以从 Flask 操作 GCS 模拟器的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号