我在sqllite表中有一些数据,我正在使用sqlalchemy进行交互。我尝试使用空白字段获取表格行,刮取空白字段的信息,然后更新行中的字段。我有:
engine = create_engine(db_path)
Base = declarative_base()
# metadata = Base.metadata
# Look up the existing tables from database
Base.metadata.reflect(engine)
def object_as_dict(obj):
return {c.key: getattr(obj, c.key)
for c in inspect(obj).mapper.column_attrs}
class Get_blank_field_spider(Spider):
def start_requests(self):
source_table= self.source
# NOTE THAT type CREATES A CLASS OF name = source_table
table = type(source_table, (Base,), {"__tablename__": source_table,
"__mapper_args__": {
"primary_key": [Base.metadata.tables[source_table].c.id]}})
Session = sessionmaker(bind=engine)
session = Session()
i = 0
s = session.query(table)
for row in s.limit(300):
i += 1
print object_as_dict(row)
d = object_as_dict(row)
yield Request(url=myurl, headers= headers, callback=self.parse_blank_field_lookup,meta={'d':d, 'cookiejar': i, 'session':s },dont_filter = True)
def parse_blank_field_lookup(self, response):
d = response.meta['d']
i = response.meta['cookiejar']
s = response.meta['session']
try:
blank_field = response.xpath('//PATH GOES HERE').extract_first()
d['blank_field']= blank_field
print d
except:
d['blank_field']= 'not found'
s.filter_by(id=d['id']).update(d)
# s.commit()
正如您所看到的那样,我通过查找正确的行并使用更新功能,在使用已删除的数据更新d后,通过传入字典(d)来尝试通过会话并更新整行。虽然没有生成错误,但这不会更新表本身中的行。我怎样才能使这个工作?