【问题标题】:DetachedInstanceError: Instance <HomeCategory > is not bound to a Session; attribute refresh operation cannot proceed [duplicate]DetachedInstanceError:实例 <HomeCategory > 未绑定到 Session;属性刷新操作无法继续[重复]
【发布时间】:2018-03-02 04:26:36
【问题描述】:

我对 Python 和 sqlalchemy 没有太多经验。 我检查了之前提出的类似问题,但我仍然无法解决我的问题。 我有一个独立的池 pgbouncer。我正在尝试使用 pgbouncer 的 sqlalchemy 前端。对于不要让连接保持打开状态,我尝试使用 contextmanager 和 with 语句。我认为我在 get_db_session() 方法中的错误。但是还是找不到。

这是我的存储库.py

import logging
import threading
from contextlib import contextmanager

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.pool import StaticPool
from sqlalchemy.pool import NullPool


@contextmanager
def get_db_session():
    try:
        engine = create_engine(
            'postgresql://superuser:@localhost:6432/testdbname', poolclass=NullPool)
        session_factory = sessionmaker(bind=engine)
        Session = scoped_session(session_factory)
        some_session = Session()
        print "got new session"
        yield some_session
        print "after yield goingt to commit"
        some_session.commit()
    except Exception as ex:
        print(ex)
        some_session.roleback()
    finally:
        some_session.expunge_all()
        some_session.close()
        print "closing"


def save(entity, _clazz=None):
    if _clazz:
        if hasattr(entity, 'id'):  # usually id is None so this method acs as normal save
            _id = entity.id
        else:
            _id = entity.name
        try:
            if _id:
                found = find(_clazz, _id)
                if found is not None:
                    if isinstance(found, list):
                        for e in found:
                            delete(e)
                    else:
                        delete(found)
        except NoResultFound:
            pass

    with get_db_session() as se:
        se.add(entity)
        se.commit()

def delete(entity):
    with get_db_session() as se:
        se.delete(entity)
        se.commit()

def find_by_element_value(_clazz, element, value):
    with get_db_session() as se:
        res = se.query(_clazz).filter(element == value).all()
        se.commit()
    return res

def get_all(_class):
    print "get_all starte"
    with get_db_session()  as se:
        print "entered with"
        res = se.query(_class).all()
        print "going to commit"
        se.commit()
    return res

我在这里使用它 test.py

import repositories as repository 
import model 

if __name__ == '__main__':
    a = repository.get_all(model.HomeCategory)
    a[0].slug

然后我得到这个错误。我不明白我的错误在哪里。

Traceback (most recent call last):
  File "/home/sahin/workspace/myspider/myspider/spiders/test.py", line 6, in <module>
    a[0].slug
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 237, in __get__
    return self.impl.get(instance_state(instance), dict_)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 579, in get
    value = state._load_expired(state, passive)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/state.py", line 592, in _load_expired
    self.manager.deferred_scalar_loader(self, toload)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/loading.py", line 644, in load_scalar_attributes
    (state_str(state)))
DetachedInstanceError: Instance <HomeCategory at 0x7f157008dd90> is not bound to a Session; attribute refresh operation cannot proceed

也许有人对此提供帮助。 谢谢。

【问题讨论】:

  • 我想我发现了一些想法。我的错是我试图从 with 语句中取出查询对象。直到我关闭并刷新数据会话。这个有效。但只有我应该找到一种方法,如何通过我的存储库中的方法获取数据。 with repository.get_db_session() as se: res = se.query(model.HomeCategory).all() for i in res: print i.slug

标签: python sqlalchemy


【解决方案1】:

您可以使用session.expire_on_commit = False,以便下次使用会话。

您也可以在scoped_session init 上设置此参数。

欲了解更多信息:Session API

【讨论】:

  • 非常感谢,伙计!它有很大帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2020-06-01
  • 2017-01-30
  • 2011-07-02
  • 1970-01-01
  • 2011-02-15
  • 2018-07-31
相关资源
最近更新 更多