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。
thx爲您的評論人 – testomet 2012-07-12 13:34:44