SQLAlchemy/Postgres中的断管错误

0 投票
1 回答
1671 浏览
提问于 2025-04-28 15:38

我有一个网络爬虫应用,它会收集数据并把这些数据存储到数据库里。整体运行还不错,但一天中会出现几次间歇性的错误,像这样:

OperationalError: (OperationalError) server closed the connection unexpectedly
This probably means the server terminated abnormally before or while processing the
request. could not send startup packet: Broken pipe

我觉得这个错误是因为下面这段代码(出错的地方)处理的数据量太大了,我不太确定该怎么优化它。

编辑:我假设这就是问题所在,并在下面提供了更多相关信息。如果这个错误还有其他原因,我也很乐意知道怎么解决它 :)

因为这是一个网络爬虫,它会定期访问一个网页来获取数据。每次访问时,它会收集大约2000到3000条记录。其中50到100条是新的,但其他记录的一些属性可能会有新信息。

还有一点值得注意:我在数据库中使用的是网络爬取数据里的一个ID作为主键,所以即使这个ID还不在数据库里,程序在创建对象时也已经知道这个ID了。

以下是带有一些注释的代码:

#objs is a list of Models of all the information it just scraped. This 
#finds the oldest timestamp in this set so I can reduce the database query.
#I don't know how many this tends to be.
earliest_scraped = min(o.timestamp for o in objs)

#create the sqlalchemy db session
session = db_setup()

#this queries the objects already in the database, reduced by the timestamp
#above so it is only objects which might overlap with what was scraped
existing = session.query(
    Model
).filter(
    Model.timestamp > earliest_scraped
)

#this merges the list of objects with the query so it updates any existing
#items and adds any new items
existing.merge_result(objs)

#commit and close
session.commit()
session.close()
暂无标签

1 个回答

0

经过很多尝试,这个崩溃似乎是因为系统内存不够用了。

这个问题是由于应用程序中的内存泄漏造成的,跟上面的代码没有关系。

撰写回答