SQLAlchemy:增加简单查询的内存

时间:2017-06-18 12:41:02

标签: python-2.7 sqlalchemy

我目前正在玩SQLAlchemy,我发现了一个关于内存使用的奇怪行为。我正在使用sqlalchemy和版本1.1.10在python 2.7.13上运行

# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

from contextlib import contextmanager

import memory_profiler
from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

e = create_engine('mysql://root:root@127.0.0.1:3306/MyDb?charset=utf8')


class Currency(Base):
    __tablename__ = "currency"
    id = Column(Integer, primary_key=True)

Base.metadata.create_all(e)
Session = sessionmaker(autoflush=True, bind=e)


@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()


@memory_profiler.profile(precision=6)
def foo():
    with session_scope() as session2:
        result = session2.query(Currency).filter_by(id=1).first()
        print(result.id)


while True:
    foo()

它的内存似乎从未被释放,并且不断增加。 memory_profiler的输出如下:

Line #    Mem usage    Increment   Line Contents
================================================
    40  53.875000 MiB   0.000000 MiB   @memory_profiler.profile(precision=6)
    41                             def foo():
    42  53.875000 MiB   0.000000 MiB       with session_scope() as session2:
    43  53.886719 MiB   0.011719 MiB           result = session2.query(Currency).filter_by(id=1).first()
    44  53.886719 MiB   0.000000 MiB           print(result.id)

Line #    Mem usage    Increment   Line Contents
================================================
    40  53.953125 MiB   0.000000 MiB   @memory_profiler.profile(precision=6)
    41                             def foo():
    42  53.953125 MiB   0.000000 MiB       with session_scope() as session2:
    43  53.957031 MiB   0.003906 MiB           result = session2.query(Currency).filter_by(id=1).first()
    44  53.957031 MiB   0.000000 MiB           print(result.id)

有没有办法解决这个问题?我已尝试使用session.expunge_all()但它似乎没有按预期工作。或者我的代码有问题吗?

0 个答案:

没有答案