【发布时间】:2018-07-04 04:34:15
【问题描述】:
我正在尝试使用 SQLAlchemy 将我的 Scrapy 抓取数据直接传输到 postgresql 数据库中。我设法建立了连接,但是没有写入任何内容,并且我在写入数据库的每个项目上都收到错误:
DETAIL: Key (hash_id)=(2122600700) already exists.
[SQL: 'UPDATE spider SET hash_id=%(hash_id)s'] [parameters: {'hash_id': 2122600700}]
这不是真的,因为我检查了我的数据库(只有 60 个项目)并且我尝试使用不同的主键 (hash_ids) 抓取项目。我必须在 SQLAlchemy 和 Scrapy 处理项目方面遗漏一些东西,这些是我的管道:
管道.py
class PgPipeline(object):
def __init__(self):
"""
Initializes database connection.
Reflects the spider table.
"""
engine = db_connect()
self.spiderDB = load_table(engine)
self.conn = engine.connect()
def process_item(self, item, spider):
"""Save listings in the database.
This method is called for every item pipeline component.
"""
stmt = self.spiderDB.update().values(item)
self.conn.execute(stmt)
return item
def close_spider(self, spider):
self.conn.close()
models.py
metadata = MetaData()
def db_connect():
"""
Performs database connection using database settings from settings.py.
Returns sqlalchemy engine instance
"""
return create_engine(URL(**settings.DATABASE))
def load_table(engine):
"""
Reflects the spider table in the DB
"""
return Table('spider', metadata, autoload=True, autoload_with=engine)
真的希望你们中的一个可以帮助我,因为我在这个问题上已经摸不着头脑了!
【问题讨论】:
-
您是否打算使用
insert而不是update?update用于修改表中已存储的条目。 -
非常感谢!这实际上开始将内容写入数据库。我正在寻找 postgresq 'upsert' 并错误地读取了更新命令将为此工作......我将不得不为该功能添加其他命令
-
“upsert”记录在方言特定部分:docs.sqlalchemy.org/en/latest/dialects/…
标签: python sqlalchemy scrapy