Boto3显示ConnectionReset Error

时间:2017-09-17 16:40:49

标签: python amazon-s3 flask boto boto3

我为每个执行查询的函数添加了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()

1 个答案:

答案 0 :(得分:0)

如果您编写装饰器并在数据库会话中执行您的方法,那将会更加清晰。像这样

def db_session():
    def wrapper(func):
        def wrapped(*args, **kwargs):
            # Executing the handler inside a db context
            with Session as session:
                try:
                    return func(session, *args, **kwargs)
                except:
                    session.rollback()

@app.route('/space/<spacename>', methods=['GET', 'POST'])
@login_required
@db_session()
def showspace(session, spacename):
    # your code