scrapy之异步写入数据库
程序员文章站
2022-05-10 19:56:32
...
1 setting.py文件,写入数据库连接属性
# mysql连接属性
MYHOST = '127.0.0.1'
MYUSER = 'root'
MYPASSWORD = '123'
MYDB = 'temp'
2 pipelines.py文件,写入管道
首先导入
# 异步数据库操作api
from twisted.enterprise import adbapi
import MySQLdb.cursors
编写管道
# 异步写入mysql pipeline
class TwistedCnblogMysqlPipeline(object):
def __init__(self,dbpool):
self.dbpool = dbpool
# 方法名是固定的,类方法,该方法优先于__init__执行
@classmethod
def from_settings(cls, settings):
db_config = dict(
#变量名固定
host = settings['MYHOST'],
user = settings['MYUSER'],
passwd = settings['MYPASSWORD'],
db = settings['MYDB'],
charset = 'utf8',
cursorclass = MySQLdb.cursors.DictCursor,
)
# 数据库连接池
dbpool = adbapi.ConnectionPool('MySQLdb' ,**db_config)
return cls(dbpool)
def process_item(self,item,spider):
# 异步插入操作
query = self.dbpool.runInteraction(self.insert,item)
query.addErrback(self.handle_error)
return item
# 插入操作
def insert(self,cursor,item):
sql = '插入语句'
cursor.execute(sql)
#错误处理函数
def handle_error(self,error):
print str(error)
3 settings.py文件,加入该管道
转载于:https://blog.51cto.com/linqi/1973828
上一篇: scrapy 异步插入数据库pipeline 通用代码
下一篇: scrapy数据库异步写入