如何使用python flask从谷歌云存储服务图像

B B*_*B B 5 python google-app-engine image flask google-cloud-storage

我目前正致力于在Appengine标准环境中运行烧瓶的项目,我正在尝试在我项目的默认Appengine存储桶中提供已上传到Google Cloud Storage的图像.

这是我目前拥有的路由代码:

# main.py

from google.appengine.api import images
from flask import Flask, send_file

app = Flask(__name__)

...

@app.route("/sample_route")
def sample_handler():
    myphoto = images.Image(filename="/gs/myappname.appspot.com/mysamplefolder/photo.jpg")
    return send_file(myphoto)
...
Run Code Online (Sandbox Code Playgroud)

但是,我收到了一个AttributeError: 'Image' object has no attribute 'read'错误.

问题是,如何使用python和flask使用任意路径提供来自谷歌云存储的图像?

编辑:

我实际上是在尝试提供我上传到我的应用引擎项目中的默认云存储桶的图像.

我还尝试使用以下代码提供图像但没有成功:

# main.py

from google.appengine.api import images
from flask import Flask, send_file

app = Flask(__name__)

...

@app.route("/sample_route")
def sample_handler():
    import cloudstorage as gcs
    gcs_file = gcs.open("/mybucketname/mysamplefolder/photo.jpg")
    img = gcs_file.read()
    gcs_file.close()

    return send_file(img, mimetype='image/jpeg')
...
Run Code Online (Sandbox Code Playgroud)

Bre*_*ttJ 6

我使用了GoogleAppEngineCloudStorageClientPython库并使用类似于以下示例的代码加载了图像:

from google.appengine.api import app_identity
import cloudstorage
from flask import Flask, send_file
import io, os

app = Flask(__name__)

# ...

@app.route('/imagetest')
def test_image():

  # Use BUCKET_NAME or the project default bucket.
  BUCKET_NAME = '/' + os.environ.get('MY_BUCKET_NAME',
                                     app_identity.get_default_gcs_bucket_name())
  filename = 'mytestimage.jpg'
  file = os.path.join(BUCKET_NAME, filename)

  gcs_file = cloudstorage.open(file)
  contents = gcs_file.read()
  gcs_file.close()

  return send_file(io.BytesIO(contents),
                   mimetype='image/jpeg')
Run Code Online (Sandbox Code Playgroud)


opy*_*ate 5

使用google-cloud-storage==1.6.0

from flask import current_app as app, send_file, abort
from google.cloud import storage
import tempfile

@app.route('/blobproxy/<filename>', methods=['GET'])
def get(filename):
    if filename:
        client = storage.Client()
        bucket = client.get_bucket('yourbucketname')
        blob = bucket.blob(filename)
        with tempfile.NamedTemporaryFile() as temp:
            blob.download_to_filename(temp.name)
            return send_file(temp.name, attachment_filename=filename)
    else:
        abort(400)
Run Code Online (Sandbox Code Playgroud)

我建议查看您的路线的或转换器的文档,并且默认为因此没有残留。 还计算出是否给它一个文件名,就像这里的情况。pathstringNamedTemporaryFiledelete=Trueflaskmimetype