Scrapy管道中的批处理/批量SQL插入[PostgreSQL]

Mor*_*war 2 python postgresql multiple-insert scrapy

我使用自己的管道将废弃的项目存储到PostgreSQL数据库中,几天前我进行了扩展,现在将数据存储到3个数据库中.所以,我想让每100个项目调用插入数据的管道,或者它取出项目并将它们插入100×100.

我想让它在数据库服务器上快速而不那么头疼的原因.

Mor*_*war 5

解决方案与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[:] = []
Run Code Online (Sandbox Code Playgroud)

然后我在管道中导入它

from project.settings import products_buffer,add_to_products_buffer,get_products_buffer_len,empty_products_buffer,get_products_buffer
Run Code Online (Sandbox Code Playgroud)

每次调用管道时我都会将项目附加到列表中,并检查列表的长度是否为100 I循环列表以准备许多插入quires但最重要的魔法是将它们全部提交到一行中,不要在循环中提交,否则你将无法获得任何东西,并且需要很长时间才能将它们全部插入.

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
Run Code Online (Sandbox Code Playgroud)

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