我有一个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'))
我的问题是,如果我从标准环境更改为弹性环境,是否可以保存到静态文件夹?如果不是,我还应该考虑其他哪些托管选项?您有什么建议吗?
提前感谢。
根据您的建议,我将更改为使用云存储。我想知道我应该从upload_from_file(),upload_from_filename()或upload_from_string()使用什么。 source_file从flask-wtform的form.photo.data获取数据。我尚未成功保存到云存储上。这是我的代码:
def upload_blob(bucket_name, source_file, destination_blob_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file)
return destination_blob_name
@app.route('/image/add', methods=['GET', 'POST'])
def addimage():
form = Form()
if form.validate_on_submit():
name = 'randomname'
try:
filename = 'foldername/'+ name + '.jpg'
picture_file = upload_blob('mybucketname', form.photo.data, filename)
return redirect(url_for('addimage'))
except:
flash("unsuccess")
return redirect(url_for('addimage'))
将其存储到某个文件夹的问题是,它将驻留在一个实例上,而其他实例将无法访问它。此外,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!')
[使用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))