2012-07-11 19 views
1

Scrapy mysql pipeline關鍵部分我需要幫助修復管道scrapy代碼中的關鍵部分。在runInteraction()

我使用scrapy這個MySQL管道(從http://snippets.scrapy.org/snippets/33/):

class SQLStorePipeline(object): 

def __init__(self): 
    self.dbpool = adbapi.ConnectionPool('MySQLdb', db='mydb', 
      user='myuser', passwd='mypass', cursorclass=MySQLdb.cursors.DictCursor, 
      charset='utf8', use_unicode=True) 

def process_item(self, item, spider): 
    # run db query in thread pool 
    query = self.dbpool.runInteraction(self._conditional_insert, item) 
    query.addErrback(self.handle_error) 

    return item 

def _conditional_insert(self, tx, item): 
    # create record if doesn't exist. 
    # all this block run on it's own thread 


    # START CRITICAL SECTION 
    some_critical_code_here 
    # STOP CRITICAL SECTION 


    tx.execute("select * from websites where link = %s", (item['link'][0],)) 
    result = tx.fetchone() 
    if result: 
     log.msg("Item already stored in db: %s" % item, level=log.DEBUG) 
    else: 
     tx.execute(\ 
      "insert into websites (link, created) " 
      "values (%s, %s)", 
      (item['link'][0], 
      datetime.datetime.now()) 
     ) 
     log.msg("Item stored in db: %s" % item, level=log.DEBUG) 

def handle_error(self, e): 
    log.err(e) 

一切工作就好了。

正如你所看到的,我已經知道我的代碼中的關鍵部分在哪裏。但我真的很新的python不知道如何使用一些鎖或類似的東西,以防止進入crical部分比一個更多的線程。

你能幫我嗎? 如果您可以向我發送輸入代碼並保留我可以在此代碼中使用的關鍵部分,那將非常好。

Thx guys。

回答

0

無論如何,我在關鍵部分 THX與合併SQL statments地傢伙整理出來尼克牙齒上的scrapy IRC的想法

1

即使您使用Twisted,通常涉及到阻塞的所有事情都需要以不同的方式完成,但您仍然處於Twisted的某個特定部分,其中阻塞是可以的。所以這應該是越簡單分配的鎖定對象,所有線程將能夠引用,然後獲得它:

import threading 

insert_critical_lock = threading.Lock() 

... 

def _conditional_insert(self, tx, item): 

    with insert_critical_lock: 
     # START CRITICAL SECTION 
     some_critical_code_here 
     # STOP CRITICAL SECTION 

    tx.execute("select * from websites where link = %s", (item['link'][0],)) 
    ... 
+0

thx爲您的評論人 – testomet 2012-07-12 13:34:44