我通读了关于会话的SQLalchemy手册,但我似乎错过了一些东西。我收到以下错误
Traceback (most recent call last):
File "every_5min.py", line 847, in <module>
cache()
File "every_5min.py", line 810, in cache
counter = harvest(harvester_date.date())
File "every_5min.py", line 247, in harvest
print object_already_exists.categories()
File "/Users/X/github/app/models.py", line 747, in categories
return [self.primary_category] + self.secondary_categories.all()
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/attributes.py", line 237, in __get__
return self.impl.get(instance_state(instance), dict_)
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/attributes.py", line 583, in get
value = self.callable_(state, passive)
File "/Library/Python/2.7/site-packages/sqlalchemy/orm/strategies.py", line 517, in _load_for_state
(orm_util.state_str(state), self.key)
sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Papers at 0x109b75190> is not bound to a Session; lazy load operation of attribute 'primary_category' cannot proceed
所以我试图使用的对象似乎不再绑定到会话了。 我正在使用flask-sqlalchemy并在使用
启动应用程序时启动会话from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
手册似乎说对象如何分离的唯一方法是会话是否关闭。但是在flask-sqlalchemy中,当应用程序运行时,会话永远不会关闭? 我读过一些关于该对象可以在提交后过期的内容,但我确保在错误发生之前我没有提交。这是我的实际代码
# Get the objects
list_of_objects = db.session.query(models.Table).filter(models.Table.id.in_(list_of_ids)).all()
# there are multiple entries with this id... use the one with the highest version number
get_attr = operator.attrgetter('id')
# create a list of lists for each id
new_list = [list(g) for k, g in itertools.groupby(sorted(list_of_objects, key=get_attr), get_attr)]
get_attr = operator.attrgetter('version')
list_of_objects = [max(dummy_list, key=get_attr) for dummy_list in new_list]
# loop through a list of records
for record in root.find(OAI+'ListRecords').findall(OAI+"record"):
# get record id
record_id = record.find(OAI+'id')
# check whether record already exists
object_already_exists = next((x for x in list_of_objects if x.id == record_id), None)
if object_already_exists:
print object_already_exists.categories()
代码运行233个记录项,然后给出上面的错误。由于它始终是233我猜它是由具体的东西触发,但我不知道是什么。据我了解会话,它应该将list_of_objects中的对象绑定到会话。 谢谢你的建议 最好的卡尔
P.S。 category属性设置为
class Table(db.Model):
id = db.Column(db.Integer)
primary_category = db.Column(db.String(1000))
...
secondary_categories = db.relationship('Object_Category', secondary=secondary_categories, lazy='dynamic')
def categories(self):
return [self.primary_category] + self.secondary_categories.all()