scrapy mysql 连接池_scrapy 如何在多个模块里共用一个数据库连接池

a65420321a

203 天前

@zdnyp

from .settings import ITEM_KEY

import json, redis

class RedisPipeline:

def __init__(self, redis_host, redis_port, redis_db):

self.redis_host = redis_host

self.redis_port = redis_port

self.redis_db = redis_db

@classmethod

def from_crawler(cls, crawler):

return cls(

redis_host=crawler.settings.get('REDIS_HOST'),

redis_port=crawler.settings.get('REDIS_PORT'),

redis_db=crawler.settings.get('REDIS_DB')

)

def open_spider(self, spider):

self.pool = redis.ConnectionPool(host=self.redis_host,

port=self.redis_port,

db=self.redis_db)

self.conn = redis.StrictRedis(connection_pool=self.pool)

print('#### pipelines.open_spider')

def close_spider(self, spider):

pass

def process_item(self, item, spider):

self.conn.rpush(ITEM_KEY, json.dumps(item))

return item

这样没错吧?

我没搞懂的是,在 middleware 和 spider 里面要怎么调用这个 self.conn 呢?

Scrapy提供了异步的Item Pipeline机制,可以方便地将数据存储到MySQL数据库中。具体实现步骤如下: 1. 安装异步MySQL库aiomysql:`pip install aiomysql` 2. 在settings.py中配置MySQL数据库信息: ``` MYSQL_HOST = 'localhost' MYSQL_PORT = 3306 MYSQL_USER = 'root' MYSQL_PASSWORD = 'password' MYSQL_DBNAME = 'database_name' ``` 3. 创建一个异步的MySQL连接池: ``` import aiomysql class MySQLPipeline(object): def __init__(self, mysql_host, mysql_port, mysql_user, mysql_password, mysql_dbname): self.mysql_host = mysql_host self.mysql_port = mysql_port self.mysql_user = mysql_user self.mysql_password = mysql_password self.mysql_dbname = mysql_dbname self.pool = None @classmethod async def from_crawler(cls, crawler): mysql_host = crawler.settings.get('MYSQL_HOST', 'localhost') mysql_port = crawler.settings.get('MYSQL_PORT', 3306) mysql_user = crawler.settings.get('MYSQL_USER', 'root') mysql_password = crawler.settings.get('MYSQL_PASSWORD', 'password') mysql_dbname = crawler.settings.get('MYSQL_DBNAME', 'database_name') obj = cls(mysql_host, mysql_port, mysql_user, mysql_password, mysql_dbname) obj.pool = await aiomysql.create_pool( host=obj.mysql_host, port=obj.mysql_port, user=obj.mysql_user, password=obj.mysql_password, db=obj.mysql_dbname, charset='utf8mb4', autocommit=True, maxsize=10, minsize=1 ) return obj async def process_item(self, item, spider): async with self.pool.acquire() as conn: async with conn.cursor() as cur: sql = "INSERT INTO table_name (field1, field2) VALUES (%s, %s)" await cur.execute(sql, (item['field1'], item['field2'])) return item async def close_spider(self, spider): self.pool.close() await self.pool.wait_closed() ``` 4. 在settings.py中启用MySQLPipeline: ``` ITEM_PIPELINES = { 'myproject.pipelines.MySQLPipeline': 300, } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值