python 異步MySQL存庫
對於異步框架而言,這些延遲是無法接受的。因此, Twisted 提供了 twisted.enterprise.adbapi, 遵循DB-API 2.0協議的一個異步封裝。
adbapi 在單獨的線程里面進行阻塞數據庫操作, 當操作完成的時候仍然通過這個線程來進行回調。同事,原始線程能繼續進行正常的工作,服務其他請求。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
# 用twisted庫將數據進行異步插入到數據庫
import
pymysql
from
twisted.enterprise
import
adbapi
from
twisted.internet
import
reactor
class
MysqlTwistedPipeline(
object
):
def
__init__(
self
, dbpool):
self
.dbpool
=
dbpool
@classmethod
def
from_settings(
cls
, settings):
# 需要在setting中設置數據庫配置參數
dbparms
=
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
,
)
# 連接ConnectionPool(使用MySQLdb連接,或者pymysql)
dbpool
=
adbapi.ConnectionPool(
"MySQLdb"
,
*
*
dbparms)
# **讓參數變成可變化參數
return
cls
(dbpool)
# 返回實例化對象
def
process_item(
self
, item, spider):
# 使用twisted將MySQL插入變成異步執行
query
=
self
.dbpool.runInteraction(
self
.do_insert, item)
# 添加異常處理
query.addCallback(
self
.handle_error)
def
handle_error(
self
, failure):
# 處理異步插入時的異常
print
(failure)
def
do_insert(
self
, cursor, item):
# 執行具體的插入
insert_sql
=
"""
insert into jobbole_artitle(name, base_url, date, comment)
VALUES (%s, %s, %s, %s)
"""
cursor.execute(insert_sql, (item[
'name'
], item[
'base_url'
], item[
'date'
], item[
'coment'
],))
|