3

我正在 Python 2.7 中构建一个 Twisted 应用程序,并尝试使用 SqlAlchemy 与数据库进行交互。我有一个正在泄漏内存的工作应用程序,但不知道如何找到泄漏。作为“也许这就是问题”,我在问我如何使用 SqlAlchemy 是否可能是泄漏的根源。我编写了一个装饰器来创建用于与数据库交互的会话。装饰器被包裹在一个接受会话作为参数的函数周围,并在这样的线程中调用:

@inlineCallbacks
def update_db(data)
    @db_scoped_session
    def process(session):
        # do SqlAlchemy work here

    # call process in thread
    result = yield threads.deferToThread(process)
defer.returnValue(result)

其中 process 是装饰器包装的函数。这是创建会话的装饰器代码:

def db_scoped_session(engine, auto_commit=True):
''' Decorator: creates a SQLAlchemy Scoped Session and passes it in to the 
method which can then pass it along to the code that
needs to operate with the db
Parameters:
  engine         a sqlalchemy configured engine to use
  auto_commit    if True, this will commit the session on successful 
                 completion (no exceptions), will otherwise rollback

                 if False, assume the wrapped function is doing the
                 commit
'''
assert engine is not None, "Must pass a valid engine parameter"
def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        results = None
        db_sessionmaker = scoped_session(sessionmaker(expire_on_commit=True, bind=engine))
        db_session = db_sessionmaker()
        try:
            results = func(db_session, *args, **kwargs)
            # should we rollback for safety?
            if not auto_commit:
                db_session.rollback()
        except:
            db_session.rollback()
            raise
        finally:
            db_session.commit()
        return results
    return wrapper
return decorator

有没有人看到我在上面做的事情有什么问题?

提前致谢!道格

4

0 回答 0