使用 Cloud Storage

您可以使用 Cloud Storage 来存储和提供文件,例如电影、图片或其他静态内容。

本文档介绍了如何在应用中使用 Google Cloud 客户端库将数据存储在 Cloud Storage 中,以及如何从 Cloud Storage 检索数据。

准备工作

  • 请按照 App Engine 上的 Python 版“Hello, World!”中的说明设置您的环境和项目,并了解如何在 App Engine 中构建 Python 应用。记下并保存项目 ID,因为您需要用它来运行本文档中介绍的示例应用。

  • 请务必调用以下命令,为您的应用创建 Cloud Storage 存储分区:

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • 将此存储分区设为可公开读取,以便其可以传送文件:

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    

下载示例

如需克隆代码库,请执行以下命令:

git clone https://github.com/GoogleCloudPlatform/python-docs-samples
cd python-docs-samples/appengine/flexible/storage

修改项目配置并安装依赖项

app.yaml 中设置 GOOGLE_STORAGE_BUCKET;此值是您之前创建的 Cloud Storage 存储分区的名称。

env_variables:
    CLOUD_STORAGE_BUCKET: your-bucket-name

请注意,您必须在 requirements.txt 中包含 google-cloud-storage 库,因为该库提供了 Cloud Storage 函数。

Flask==2.1.0; python_version > '3.6'
Flask==2.0.3; python_version < '3.7'
werkzeug==2.1.2; python_version > '3.6'
werkzeug==2.0.3; python_version < '3.7'
google-cloud-storage==2.0.0; python_version < '3.7'
google-cloud-storage==2.1.0; python_version > '3.6'
gunicorn==20.1.0; python_version > '3.0'
gunicorn==19.10.0; python_version < '3.0'

应用代码

示例应用提供了一个网页,用于提示用户提供要存储在 Cloud Storage 中的文件。在用户选择文件并点击“提交”后,上传处理程序会将文件内容加载到一个 Cloud Storage blob 中,并将其写入 Cloud Storage 储分区

请注意,在将文件上传到 Cloud Storage 后,系统将返回此文件的公开网址,您可以使用该网址直接从 Cloud Storage 传送文件。您应将此值存储在应用中以备将来使用。

import logging
import os
from typing import Union

from flask import Flask, request
from google.cloud import storage

app = Flask(__name__)

# Configure this environment variable via app.yaml
CLOUD_STORAGE_BUCKET = os.environ['CLOUD_STORAGE_BUCKET']

@app.route('/')
def index() -> str:
    return """
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
"""

@app.route('/upload', methods=['POST'])
def upload() -> str:
    """Process the uploaded file and upload it to Google Cloud Storage."""
    uploaded_file = request.files.get('file')

    if not uploaded_file:
        return 'No file uploaded.', 400

    # Create a Cloud Storage client.
    gcs = storage.Client()

    # Get the bucket that the file will be uploaded to.
    bucket = gcs.get_bucket(CLOUD_STORAGE_BUCKET)

    # Create a new blob and upload the file's content.
    blob = bucket.blob(uploaded_file.filename)

    blob.upload_from_string(
        uploaded_file.read(),
        content_type=uploaded_file.content_type
    )

    # Make the blob public. This is not necessary if the
    # entire bucket is public.
    # See https://cloud.google.com/storage/docs/access-control/making-data-public.
    blob.make_public()

    # The public URL can be used to directly access the uploaded file via HTTP.
    return blob.public_url

@app.errorhandler(500)
def server_error(e: Union[Exception, int]) -> str:
    logging.exception('An error occurred during a request.')
    return """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(e), 500

if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)

了解详情

如需全面了解 Cloud Storage,请参阅 Cloud Storage 文档