1.twisted框架介紹
Twisted是用Python實(shí)現(xiàn)的基于事件驅(qū)動(dòng)的網(wǎng)絡(luò)引擎框架鸳兽;
Twisted支持許多常見(jiàn)的傳輸及應(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/
2.MySQL數(shù)據(jù)庫(kù)信息保存到settings文件中
- 首先我們需要把MySQL數(shù)據(jù)庫(kù)中的配置信息保存到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ù)庫(kù)
首先創(chuàng)建一個(gè)用于異步寫入數(shù)據(jù)的AIOMysqlItemPipeline類涯保,然后在這個(gè)類的初始化方法中創(chuàng)建一個(gè)pool連接池诉濒;
然后在
from_settings()方法
中獲取settings文件中的數(shù)據(jù)庫(kù)配置信息,并將配置信息存入一個(gè)字典中夕春。使用Twisted中的adbapi獲取數(shù)據(jù)庫(kù)連接池對(duì)象未荒,使用前需要導(dǎo)入adbapi,如:from twisted.enterprise import adbapi
及志。使用時(shí)需要用到ConnectionPool連接池:pool=adbapi.ConnectionPool('MySQLdb',**params)
片排,參數(shù)MySQLdb是使用的數(shù)據(jù)庫(kù)引擎的名字,params就是要傳遞的數(shù)據(jù)庫(kù)配置信息困肩;接著在process_item()方法中使用數(shù)據(jù)庫(kù)連接池對(duì)象進(jìn)行數(shù)據(jù)庫(kù)操作划纽,自動(dòng)傳遞cursor對(duì)象到數(shù)據(jù)庫(kù)操作方法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的頁(yè)面
'XKD_Dribbble_Spider.pipelines.ImagePipeline': 1,
'XKD_Dribbble_Spider.pipelines.AIOMysqlItemPipeline': 2,
}