如何在Google Cloud上从私有存储桶中提供图片/文件

时间:2019-07-20 10:03:19

标签: google-app-engine flask google-cloud-storage

我一直在努力寻找如何从App Engine存储桶(或任何私有存储桶)中获取图像并将其显示在运行于GCP App Engine上的Flask网站上的方法。

我正在尝试以下变化:

@app.route('/get_object/<object>')
def get_object(object):
    client = storage.Client()
    bucket = client.get_bucket('bucket-id')
    blob = bucket.get_blob(object)

    return blob

我的HTML看起来像这样:

<img src={{ url_for('get_object', object='test.jpg') }}>

在我的App Engine默认存储桶中,我坐在一张名为test.jpg的照片上,但似乎没有任何效果。我的存储桶必须是私有的,反正还有可以提供私有文件​​的文件吗?

1 个答案:

答案 0 :(得分:1)

我这样做了:

我的图片src使用python函数传递存储桶和对象

<img src="{{ url_for('get_file', bucket='testBucket', object='image.png') }}">

这是功能

@app.route('/get_file/<testBucket>/<object>')
@requires_auth
def get_file(testBucket, object):

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(testBucket)
    blob = bucket.blob(object)

    with tempfile.TemporaryDirectory() as tmpdirname:
        fullpath = os.path.join(tmpdirname, object)
        blob.download_to_filename(fullpath)
        return send_from_directory(tmpdirname, object)

这会将App Engine应用程序本地的文件保存在一个临时目录中,该函数一旦返回就存在,该目录将被删除,因此用户可以获取文件,但临时位置不再存在。我认为...

相关问题