【发布时间】:2017-09-18 01:05:44
【问题描述】:
我为每个执行查询的函数添加了一个 db.session.close()。查找错误还向我显示,由于与 S3 的连接丢失,其他人也遇到了这个问题。在本地它工作得很好。但是在带有 mod_wsgi 和 Apache2 的 Ubuntu 服务器上运行相同的程序会显示以下错误:
185.27.213.237 - - [17/Sep/2017 16:31:34] "GET / HTTP/1.1" 200 -
185.27.213.237 - - [17/Sep/2017 16:31:39] "POST / HTTP/1.1" 302 -
('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))
185.27.213.237 - - [17/Sep/2017 16:31:50] "GET /space/user HTTP/1.1" 200 -
来自 Apache 日志:
[wsgi:error] [pid 1456:tid 139792612300544] ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))
第一行是我打开登录路径。使用正确的凭据登录后,它会显示 302 错误。在下文中,我发布了我的登录路线和成功登录后重定向到的站点。我正在使用 sqlite3,因为我只有几个用户。
#Login
@app.route('/', methods=['GET', 'POST'])
def index():
form = LoginForm()
try:
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=False)
return redirect(url_for('showspace', spacename=user.username))
return render_template('login.html', form=form, ermsg="Invalid credentials")
return render_template('login.html', form=form)
except Exception as ermsg:
db.session.rollback()
print(ermsg)
return redirect(url_for('index'))
finally:
db.session.close()
#Dashboard new
@app.route('/space/<spacename>', methods=['GET', 'POST'])
@login_required
def showspace(spacename):
try:
selectedspace=spacename
spacelist = Space.query.filter(Space.owner.any(id=current_user.id)).all()
hasaccess = User.query.join(User.spaces).filter(User.username==current_user.username, Space.name==selectedspace).first()
if hasaccess != None:
conn = boto3.resource('s3')
mybucket = conn.Bucket(selectedspace)
return render_template('dashboard.html', spaces=spacelist, filelist=mybucket.objects.all(), name=current_user.username, selectedspace=selectedspace)
else:
return "You don't have permission to view this space!"
except:
db.session.rollback()
return 'Something went wrong'
finally:
db.session.close()
【问题讨论】:
-
数据库连接不会被关闭,因为由于更早的
return,finally 没有运行。 -
我觉得跟Boto3有关系。我已经编辑了我的问题。很高兴知道 finally 甚至没有被执行。我将在每个 try 块的末尾添加 db.session.close() 。谢谢。
-
@KlausD.:那不是真的。无论
return如何,finally块都将运行。 Here's the documentation. -
@ZachGates 我想知道它应该如何工作,同时继续和返回。
标签: python amazon-s3 flask boto boto3