溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用異步的twisted框架寫入數(shù)據(jù)

發(fā)布時(shí)間:2020-08-08 20:31:10 來源:ITPUB博客 閱讀:298 作者:Winter 欄目:編程語言

1.twisted框架介紹

  • Twisted是用Python實(shí)現(xiàn)的基于事件驅(qū)動(dòng)的網(wǎng)絡(luò)引擎框架;

  • Twisted支持許多常見的傳輸及應(yīng)用層協(xié)議,包括TCP、UDP、SSL/TLS、HTTP、IMAP、SSH、IRC以及FTP。就像Python一樣,Twisted也具有“內(nèi)置池”(batteries-included)的特點(diǎn)。Twisted對(duì)于其支持的所有協(xié)議都帶有客戶端和服務(wù)器實(shí)現(xiàn),同時(shí)附帶有基于命令行的工具,使得配置和部署產(chǎn)品級(jí)的Twisted應(yīng)用變得非常方便。

  • 官網(wǎng)地址: https://twistedmatrix.com/trac/

mysql-settings-"> 2.MySQL數(shù)據(jù)庫信息保存到settings文件中

  • 首先我們需要把MySQL數(shù)據(jù)庫中的配置信息保存到settings文件中,如: MYSQL_HOST = 'localhost' 的形式;

MYSQL_HOST = 'localhost'
MYSQL_USER = 'xkd'
MYSQL_PASSWORD = '123456'
MYSQL_DATABASE = 'item_database'
MYSQL_PORT = 3306
MYSQL_OPTIONAL = dict(
    USE_UNICODE = True,
    CHARSET = 'utf8',
)

  • 然后從settings文件中將這些信息導(dǎo)入到pipeline.py文件中使用;

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.創(chuàng)建異步Pipeline寫入數(shù)據(jù)庫

  • 首先創(chuàng)建一個(gè)用于異步寫入數(shù)據(jù)的AIOMysqlItemPipeline類,然后在這個(gè)類的初始化方法中創(chuàng)建一個(gè)pool連接池;

  • 然后在 from_settings()方法 中獲取settings文件中的數(shù)據(jù)庫配置信息,并將配置信息存入一個(gè)字典中。使用Twisted中的adbapi獲取數(shù)據(jù)庫連接池對(duì)象,使用前需要導(dǎo)入adbapi,如: from twisted.enterprise import adbapi 。使用時(shí)需要用到ConnectionPool連接池: pool=adbapi.ConnectionPool('MySQLdb',**params) ,參數(shù)MySQLdb是使用的數(shù)據(jù)庫引擎的名字,params就是要傳遞的數(shù)據(jù)庫配置信息;

  • 接著在process_item()方法中使用數(shù)據(jù)庫連接池對(duì)象進(jìn)行數(shù)據(jù)庫操作,自動(dòng)傳遞cursor對(duì)象到數(shù)據(jù)庫操作方法runInteraction()的第一個(gè)參數(shù)(自定義方法)如: ret=self.connection_pool.runInteraction(self.mysql_insert,item)

  • 還可以設(shè)置出錯(cuò)時(shí)的回調(diào)方法,自動(dòng)傳遞出錯(cuò)消息對(duì)象failure到錯(cuò)誤處理方法的第一個(gè)參數(shù)(自定義方法)如: ret.addErrback(self.error_callback) ;

  • 最后記得修改settings文件中的ITEM_PIPELINES配置,如: 'XKD_Dribbble_Spider.pipelines.AIOMysqlItemPipeline': 2 ;


from twisted.enterprise import adbapi
import MySQLdb.cursors
class AIOMysqlItemPipeline:
    def __init__(self, pool):
        self.connection_pool = pool
    # 1:調(diào)用類方法
    @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:執(zhí)行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,
   # 當(dāng)items.py模塊yield之后,默認(rèn)就是下載image_url的頁面
   'XKD_Dribbble_Spider.pipelines.ImagePipeline': 1,
   'XKD_Dribbble_Spider.pipelines.AIOMysqlItemPipeline': 2,
}

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

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI