将图像文件保存在文件系统Google App引擎Python Flask中

问题描述 投票:0回答:3

我有一个flask应用程序,用户可以上传图像,并且该图像保存在文件系统上的静态文件夹中。目前。我使用Google App Engine进行托管,发现无法将其保存到标准环境中的静态文件夹中。这是代码

def save_picture(form_picture,name):
    picture_fn = name + '.jpg'
    picture_path = os.path.join(app.instance_path, 'static/image/'+ picture_fn)
    output_size = (1000,1000)
    i = Image.open(form_picture)
    i.thumbnail(output_size)
    i.save(picture_path)
    return picture_path

@app.route('/image/add', methods=['GET', 'POST'])
def addimage():
    form = Form()
    if form.validate_on_submit():
        name = 'randomname'
        try:
            picture_file = save_picture(form.image.data,name)
            return redirect(url_for('addimage'))
        except:
            flash("unsuccess")
            return redirect(url_for('addimage'))

我的问题是,如果我从标准环境更改为弹性环境,是否可以保存到静态文件夹?如果没有,我应该考虑其他哪些托管选项?你有什么建议吗。在此先感谢

google-app-engine flask python-3.7 cloud-hosting
3个回答
1
投票

将其存储到某个文件夹的问题是,它将驻留在一个实例上,而其他实例将无法访问它。此外,GAE中的实例来来往往,因此最终将丢失图像。

您应该为此使用Google Cloud Storage:

from google.cloud import storage
client = storage.Client()
bucket = client.get_bucket('bucket-id-here')
blob = bucket.get_blob('remote/path/to/file.txt')
blob.upload_from_string('New contents!')

https://googleapis.dev/python/storage/latest/index.html


0
投票

[使用Flask和Appengine,Python3.7,我通过以下方式将文件保存到存储桶中,因为我想循环处理许多文件:

for key, upload in request.files.items():
    file_storage = upload
    content_type = None
    identity = str(uuid.uuid4()) # or uuid.uuid4().hex
    try:
        upload_blob("f00b4r42.appspot.com", request.files[key], identity, content_type=upload.content_type)

助手功能:

from google.cloud import storage

def upload_blob(bucket_name, source_file_name, destination_blob_name, content_type="application/octet-stream"):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_file(source_file_name, content_type=content_type)
    blob.make_public()

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))

0
投票

从Google App Engine标准环境更改为Google App Engine灵活环境后,您可以写入磁盘,还可以为特定应用程序[1]选择具有更多内存的Compute Engine计算机类型。如果您对遵循此路径感兴趣,请查找有关迁移Python应用程序here的所有相关文档。

尽管如此,根据用户的负载,创建实例(按比例放大实例数)或删除实例(按比例缩小实例@@ Alex的用户提供的答案进行了解释,您的更好的选择是具体情况是使用云存储。查找使用Python here将对象上传到Cloud Storage的示例。

© www.soinside.com 2019 - 2024. All rights reserved.