【发布时间】:2023-04-08 12:42:01
【问题描述】:
以下代码在本地机器上以及在 AWS Elastic BeanStalk 上的部署中都能出色地工作 - 提供固定图像以及动态创建的图像。但是,一旦我将部署扩展到多个 EC2 实例,动态创建的图像就会变得不可用,即使我可以(通过 ssh)找到该动态图像存在于 EC2 实例中!
我怀疑,这与我在 html 中引用静态图像的方式或负载平衡器处理静态图像的方式有关。但是,不知道从哪里开始调查。请帮忙! :(
<code>
from flask import Flask, render_template, request, url_for
import os, datetime
import thread
import time
from copy import deepcopy
import pyqrcode # generating image of QR code from given string
application = Flask(__name__)
class QR(object):
def __init__(self):
self.input_string = None
self.output_string = None
self.input_image_filename = None
def encode(self, input_string, QR_image_filename, QR_image_scale):
"""Return the image of QR code"""
if not input_string:
raise RuntimeError('Input string is empty!') # checking that input_string is not empty
else:
self.input_string = input_string
try:
qr = pyqrcode.create(self.input_string)
qr.png(QR_image_filename, scale=QR_image_scale)
return True
except Exception as e:
print "printing exception : " + str(e)
raise RuntimeError('QR creation failed!')
def background_deletion_task(path):
print "wait starts"
# gevent.sleep(5)
time.sleep(5)
print "wait done"
if os.path.exists(path):
os.remove(path)
print "deletion done"
@application.route('/')
def hello():
gen_qr = QR()
gen_qr.qr_time = datetime.datetime.utcnow().isoformat()
gen_qr.image_file_name = str(gen_qr.qr_time[-6:]) + ".png"
gen_qr.full_path = os.path.join(application.root_path, 'static', gen_qr.image_file_name)
gen_qr.encode(str(gen_qr.image_file_name), gen_qr.full_path, 4)
# ---------------deletion by thread------------
#thread.start_new_thread(background_deletion_task, (gen_qr.full_path,))
return render_template('hello.html', gen_qr = gen_qr)
if __name__ == "__main__":
#application.debug=True
application.run()
</code>
<html>
<body>
Fixed Image
<img src="/static/EYN_Logo.png" style="max-width: 150px;">
Dynamically Created Image
<img src="/static/{{gen_qr.image_file_name}}">
</body>
</html>
【问题讨论】:
标签: python-2.7 amazon-web-services flask amazon-elastic-beanstalk autoscaling