python如何通過twisted實現(xiàn)數(shù)據(jù)庫異步插入
更新時間:2018年03月20日 11:41:32 作者:北門吹雪
這篇文章主要為大家詳細(xì)介紹了python如何通過twisted實現(xiàn)數(shù)據(jù)庫異步插入,具有一定的參考價值,感興趣的小伙伴們可以參考一下
如何通過twisted實現(xiàn)數(shù)據(jù)庫異步插入?
1. 導(dǎo)入adbapi
2. 生成數(shù)據(jù)庫連接池
3. 執(zhí)行數(shù)據(jù)數(shù)據(jù)庫插入操作
4. 打印錯誤信息,并排錯
#!/usr/bin/python3 __author__ = 'beimenchuixue' __blog__ = 'http://www.cnblogs.com/2bjiujiu/' import pymysql from twisted.enterprise import adbapi from twisted.internet import reactor def go_insert(cursor, sql): # 對數(shù)據(jù)庫進(jìn)行插入操作,并不需要commit,twisted會自動幫我commit try: for i in range(10): data = str(i) cursor.execute(sql, data) except Exception as e: print(e) def handle_error(failure): # 打印錯誤 if failure: print(failure) if __name__ == '__main__': # 數(shù)據(jù)庫基本配置 db_settings = { 'host': 'localhost', 'db': 'jobole', 'user': 'root', 'password': 'passwort', 'charset': 'utf8', 'use_unicode': True } # sql語句模版 insert_sql = 'insert into test_1(text_1) value(%s)' # 普通方法插入數(shù)據(jù) # conn = pymysql.connect(**db_settings) # cursor = conn.cursor() # cursor.execute(insert_sql, '1') # conn.commit() try: # 生成連接池 db_conn = adbapi.ConnectionPool('pymysql', **db_settings) # 通過連接池執(zhí)行具體的sql操作,返回一個對象 query = db_conn.runInteraction(go_insert, insert_sql) # 對錯誤信息進(jìn)行提示處理 query.addCallbacks(handle_error) except Exception as e: print(e) # 定時,給4秒時間讓twisted異步框架完成數(shù)據(jù)庫插入異步操作,沒有定時什么都不會做 reactor.callLater(4, reactor.stop) reactor.run()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- python如何通過twisted搭建socket服務(wù)
- Python3.6中Twisted模塊安裝的問題與解決
- python安裝twisted的問題解析
- python基于twisted框架編寫簡單聊天室
- python 編程之twisted詳解及簡單實例
- Python 基于Twisted框架的文件夾網(wǎng)絡(luò)傳輸源碼
- 剖析Python的Twisted框架的核心特性
- 實例解析Python的Twisted框架中Deferred對象的用法
- 詳解Python的Twisted框架中reactor事件管理器的用法
- 使用Python的Twisted框架編寫非阻塞程序的代碼示例
- Python的Twisted框架中使用Deferred對象來管理回調(diào)函數(shù)
- 使用Python的Twisted框架構(gòu)建非阻塞下載程序的實例教程
- Python的Twisted框架上手前所必須了解的異步編程思想
- 使用Python的Treq on Twisted來進(jìn)行HTTP壓力測試
- 利用Python的Twisted框架實現(xiàn)webshell密碼掃描器的教程
- 使用Python的Twisted框架實現(xiàn)一個簡單的服務(wù)器
- 使用Python的Twisted框架編寫簡單的網(wǎng)絡(luò)客戶端
- python開發(fā)實例之Python的Twisted框架中Deferred對象的詳細(xì)用法與實例
相關(guān)文章
python實現(xiàn)簡易學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)簡易學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-09-09Python網(wǎng)絡(luò)請求庫requests的10個基本用法
今天我們要聊聊Python中非常實用的一個庫——requests,這個庫讓發(fā)送HTTP請求變得超級簡單,無論你是想抓取網(wǎng)頁數(shù)據(jù)還是測試API接口,requests都能派上大用場,下面我們就一起來看看如何使用requests完成一些常見的任務(wù),需要的朋友可以參考下2024-10-10Python添加時間軸以實現(xiàn)動態(tài)繪圖詳解
這篇文章主要為大家詳細(xì)介紹了Python如何添加時間軸以實現(xiàn)動態(tài)繪圖,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以參考一下2023-09-09