python学习

Python学习八十七天:使用异步的twisted框架写入数据

2019-05-17  本文已影响14人  暖A暖

1.twisted框架介绍

2.MySQL数据库信息保存到settings文件中

MYSQL_HOST = 'localhost'
MYSQL_USER = 'xkd'
MYSQL_PASSWORD = '123456'
MYSQL_DATABASE = 'item_database'
MYSQL_PORT = 3306
MYSQL_OPTIONAL = dict(
    USE_UNICODE = True,
    CHARSET = 'utf8',
)
from .settings import MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, MYSQL_PORT, MYSQL_OPTIONAL
class MysqlPipeline:
    def __init__(self):
        self.conn = MySQLdb.connect(host=MYSQL_HOST, user=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DATABASE, use_unicode=MYSQL_OPTIONAL.get('USE_UNICODE'), charset=MYSQL_OPTIONAL.get('CHARSET'))
        self.cursor = self.conn.cursor()
    def process_item(self, item, spider):
        sql = 'insert into item(title, image_url, date, image_path, url, url_id)' \
              'values (%s, %s, %s, %s, %s, %s)'
        date = item['date']
        self.cursor.execute(sql, args=(item['title'], item['image_url'], date, item['image_path'], item['url'], item['url_id']))
        self.conn.commit()
        return item
    def spider_closed(self, spider):
        self.cursor.close()
        self.conn.close()

3.创建异步Pipeline写入数据库

from twisted.enterprise import adbapi
import MySQLdb.cursors
class AIOMysqlItemPipeline:
    def __init__(self, pool):
        self.connection_pool = pool
    # 1:调用类方法
    @classmethod
    def from_settings(cls, settings):
        connkw = {
            'host': MYSQL_HOST,
            'user': MYSQL_USER,
            'password': MYSQL_PASSWORD,
            'db': MYSQL_DATABASE,
            'port': MYSQL_PORT,
            'use_unicode': MYSQL_OPTIONAL.get('USE_UNICODE'),
            'charset': MYSQL_OPTIONAL.get('CHARSET'),
            'cursorclass': MySQLdb.cursors.DictCursor,
        }
        pool = adbapi.ConnectionPool('MySQLdb', **connkw)
        return cls(pool)
    # 2:执行process_item
    def process_item(self, item, spider):
        ret = self.connection_pool.runInteraction(self.mysql_insert, item)
        ret.addErrback(self.error_callback)
    def mysql_insert(self, cursor, item):
        sql = 'insert into item(title, image_url, date, image_path, url, url_id)' \
              'values (%s, %s, %s, %s, %s, %s)'
        date = item['date']
        cursor.execute(sql, args=(item['title'], item['image_url'], date, item['image_path'], item['url'], item['url_id']))
    def error_callback(self, error):
        print('insert_error =========== {}'.format(error))
修改settings文件
ITEM_PIPELINES = {
   # 'XKD_Dribbble_Spider.pipelines.XkdDribbbleSpiderPipeline': 300,
   # 当items.py模块yield之后,默认就是下载image_url的页面
   'XKD_Dribbble_Spider.pipelines.ImagePipeline': 1,
   'XKD_Dribbble_Spider.pipelines.AIOMysqlItemPipeline': 2,
}

参考:https://www.9xkd.com/user/plan-view.html?id=1784587600

上一篇 下一篇

猜你喜欢

热点阅读