【发布时间】:2019-04-03 19:29:36
【问题描述】:
我有一个烧瓶路由,它应该向浏览器生成服务器事件。基本上该功能的作用是: 1.加载一个csv文件 2.对于csv文件的每一行 3.在sql数据库中保存用户名和电子邮件(使用sqlalchemy) 4.更新计数器(用于进度状态) 5. 向浏览器发送事件
问题是,当我处于开发模式(使用烧瓶内置服务器)但在生产模式(使用 NginX 和 gunicorn)时,该功能运行良好,几秒钟后该功能停止,因此计数器永远不会到达100,它导致浏览器再次调用该函数,并且这个循环永远不会结束,因为事件永远不会得到关闭语句。所以主要的问题是,为什么它在开发中而不是在生产中有效? 这是mi代码:
# Update or construct database if a csv file was submitted
@app.route("/constructDatabase/<string:filename>", methods=["GET","POST"])
def constructDatabase(filename):
# context manager to open csv file
csvFile = open(os.path.join(os.getcwd(), filename), newline='')
# get lines count of csv file
totalLines = len(csvFile.readlines())
# reset reader pointer
csvFile.seek(0)
# current percent status
current_status = 0
def generate(file, counter):
# unpack and iterate over the csv file to get all the names and emails
for Company,Address,City,State,Zip,County,Phone,Website,Contact,Title,Direct_Phone,Email,Sales,Employees,SIC_Code,Industry in csv.reader(file, delimiter=','):
yield ':keep connection alive\n\n'
counter += 1
# if a user has not contact name or email then not useful
if Email == None or Email == '':
yield f'id: {counter}\nevent: message\ndata: {round(counter / totalLines * 100, 1)}\n\n'
continue
if Contact == None or Contact == '':
yield f'id: {counter}\nevent: message\ndata: {round(counter / totalLines * 100, 1)}\n\n'
continue
# Create user as instance of User class
user = Users(company=Company, address=Address, city=City, state=State,
zip=Zip, country=County, phone=Phone, website=Website, contact=Contact,
title=Title, direct_phone = Direct_Phone, email=Email, sales=Sales,
employees=Employees, sic_code=SIC_Code, industry=Industry)
# Add user to database
db.session.add(user)
# get current percent status of building database
yield f'id: {counter}\nevent: message\ndata: {round(counter / totalLines * 100, 1)}\n\n'
# Save changes in database
db.session.commit()
print("SAVING DATABASE .......")
# close file
file.close()
return Response(generate(csvFile, current_status), mimetype='text/event-stream')
Java 脚本代码现在:
javascript
// create Event source connection with the server to listen for incoming msg
var source = new EventSource(`/constructDatabase/${filename}`);
// if new msg was received
source.onmessage = function(msg) {
// update progress bar
$('.progress-bar').css('width', msg.data+'%').attr('aria-valuenow', msg.data);
// if is 100 percent close connection to the server
if (msg.data == 100) {
source.close();
// Hide label
$('.prog-bar-label').addClass('d-none');
// Hide CSV progress bar
$('.csvProgressBar').addClass('d-none');
// reset progress bar
$('.csvProgressBar').find('.progress-bar').css('width', 0+'%').attr('aria-valuenow', 0);
}
};
source.onerror = function(error){
console.log(error.data);
};
【问题讨论】:
-
检查 nginx 和 gunicorn 日志,看看哪一个可能正在关闭请求并返回结果。
-
每次重置连接时都会出现此错误:
[error] 14186#14186: *13628 connect() failed (111: Connection refused) while connecting to upstream
标签: python python-3.x nginx flask gunicorn