python - Scrapy 管道中的批量/批量 SQL 插入 [PostgreSQL]

标签 python postgresql scrapy multiple-insert

我正在使用自己的管道将抓取的项目存储到 PostgreSQL 数据库中,几天前我进行了扩展,现在将数据存储到 3 个数据库中。所以,我想制作插入数据的管道,每 100 个项目调用一次,或者它获取项目并将它们 100 x 100 插入。

我想让它在数据库服务器上变得更快和更少麻烦的原因。

最佳答案

解决方案与 Anandhakumar 的回答没有什么不同 我在设置文件中创建了一个全局列表,并为其设置了一个 setter 和 getter 方法

# This buffer for the bluk insertion
global products_buffer

products_buffer = []

# Append product to the list
def add_to_products_buffer(product):
  global products_buffer
  products_buffer.append(product)

# Get the length of the product
def get_products_buffer_len():
  global products_buffer
  return len(products_buffer)

# Get the products list
def get_products_buffer():
  global products_buffer
  return products_buffer

# Empty the list
def empty_products_buffer():
  global products_buffer
  products_buffer[:] = []

然后我在管道中导入了它

from project.settings import products_buffer,add_to_products_buffer,get_products_buffer_len,empty_products_buffer,get_products_buffer

每次调用管道时我都会将项目附加到列表中,我检查列表的长度是否为 100 我在列表上循环以准备许多插入请求,但最重要的魔法是将它们全部提交一行,不要在循环中提交,否则您将一无所获,并且将它们全部插入将花费很长时间。

def process_item(self, item, spider):  
    # Adding the item to the list
    add_to_products_buffer(item)
    # Check if the length is 100
    if get_products_buffer_len() == 100:
        # Get The list to loop on it
        products_list  = get_products_buffer()
        for item in products_list:
            # The insert query
            self.cursor.execute('insert query')
        try:
            # Commit to DB the insertions quires 
            self.conn.commit()
            # Emty the list
            empty_products_buffer()
        except Exception, e:
            # Except the error

如果你不想循环,你也可以使用executemany

关于python - Scrapy 管道中的批量/批量 SQL 插入 [PostgreSQL],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29063215/

相关文章:

python - 在 sympy 绘图中,如何获得具有固定纵横比的绘图?

java - Python 相当于 Java 抽象类吗?

python - django-tables2:向表格添加滚动条

python - 语法错误 : Non-ASCII character '\xd1' in file modules/commands.

SQL 最大值和分组依据

java - Hibernate 与 order by 不同

postgresql - 传表给postgreSQL函数,执行select语句,返回表

python - 如何在 django View 中使用参数运行 scrapy 蜘蛛

python - 云端的 Scrapy

xpath - Scrapy:在Xpath中处理Abbr标签的问题