溫馨提示×

溫馨提示×

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

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

Python中如何實現(xiàn)Scrapy+adbapi提高數(shù)據(jù)庫寫入效率

發(fā)布時間:2021-10-21 11:49:07 來源:億速云 閱讀:149 作者:柒染 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)Python中如何實現(xiàn)Scrapy+adbapi提高數(shù)據(jù)庫寫入效率,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

一:twisted中的adbapi

       數(shù)據(jù)庫pymysql的commit()和execute()在提交數(shù)據(jù)時,都是同步提交至數(shù)據(jù)庫,由于scrapy框架數(shù)據(jù)的解析和異步多線程的,所以scrapy的數(shù)據(jù)解析速度,要遠高于數(shù)據(jù)的寫入數(shù)據(jù)庫的速度。如果數(shù)據(jù)寫入過慢,會造成數(shù)據(jù)庫寫入的阻塞,影響數(shù)據(jù)庫寫入的效率。
使用twisted異步IO框架,實現(xiàn)數(shù)據(jù)的異步寫入,通過多線程異步的形式對數(shù)據(jù)進行寫入,可以提高數(shù)據(jù)的寫入速度。

1.1 兩個主要方法

adbapi.ConnectionPool:

創(chuàng)建一個數(shù)據(jù)庫連接池對象,其中包括多個連接對象,每個連接對象在獨立的線程中工作。adbapi只是提供了異步訪問數(shù)據(jù)庫的編程框架,再其內(nèi)部依然使MySQLdb這樣的庫訪問數(shù)據(jù)庫。

dbpool.runInteraction(do_insert,item):

異步調(diào)用do_insert函數(shù),dbpool會選擇連接池中的一個連接對象在獨立線程中調(diào)用insert_db,其中參數(shù)item會被傳給do_insert的第二個參數(shù),傳給do_insert的第一個參數(shù)是一個Transaction對象,其接口與Cursor對象類似,可以調(diào)用execute方法執(zhí)行SQL語句,do_insert執(zhí)行后,連接對象會自動調(diào)用commit方法

1.2 使用實例

from twisted.enterprise import adbapi
# 初始化數(shù)據(jù)庫連接池(線程池)
# 參數(shù)一:mysql的驅(qū)動
# 參數(shù)二:連接mysql的配置信息
dbpool = adbapi.ConnectionPool('pymysql', **params)
# 參數(shù)1:在異步任務(wù)中要執(zhí)行的函數(shù)insert_db;
# 參數(shù)2:給該函數(shù)insert_db傳遞的參數(shù)
query = self.dbpool.runInteraction(self.do_insert, item)
# 在execute()之后,不需要再進行commit(),連接池內(nèi)部會進行提交的操作。
def do_insert(self, cursor, item):
    insert_sql = """
            insert into qa_sample( 
            need_id, 
            need_question_uptime, 
            need_title, 
            need_title_describe, 
            need_answer_uptime, 
            need_answer)
            values (%s, %s, %s, %s, %s, %s)
            """
    params = (item['need_id'],
              item['need_question_uptime'],
              item['need_title'],
              item['need_title_describe'],
              item['need_answer_uptime'],
              item['need_answer'])
    cursor.execute(insert_sql, params)

二:結(jié)合scrapy中的pipelines

# -*- coding: utf-8 -*-
from twisted.enterprise import adbapi
import pymysql
 
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
 
 
class QaSpiderPipeline(object):
    def process_item(self, item, spider):
        return item
 
class MysqlTwistedPipeline(object):
    def __init__(self, dbpool):
        self.dbpool = dbpool
 
    @classmethod
    def from_settings(cls, settings):
        dbparams = dict(
            host=settings['MYSQL_HOST'],
            db=settings['MYSQL_DBNAME'],
            user=settings['MYSQL_USER'],
            passwd=settings['MYSQL_PASSWORD'],
            charset='utf8',
            cursorclass=pymysql.cursors.DictCursor,
            use_unicode=True
        )
        dbpool = adbapi.ConnectionPool('pymysql', **dbparams)
        return cls(dbpool)
 
    def process_item(self, item, spider):
        query = self.dbpool.runInteraction(self.do_insert, item)
 
    def do_insert(self, cursor, item):
        insert_sql = """
                insert into qa_sample( 
                need_id, 
                need_question_uptime, 
                need_title, 
                need_title_describe, 
                need_answer_uptime, 
                need_answer)
                values (%s, %s, %s, %s, %s, %s)
                """
        params = (item['need_id'],
                  item['need_question_uptime'],
                  item['need_title'],
                  item['need_title_describe'],
                  item['need_answer_uptime'],
                  item['need_answer'])
        cursor.execute(insert_sql, params)

看完上述內(nèi)容,你們對Python中如何實現(xiàn)Scrapy+adbapi提高數(shù)據(jù)庫寫入效率有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

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

AI