網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
背景
由于不同乙方對(duì)服務(wù)商業(yè)務(wù)接口字段理解不一致,導(dǎo)致線(xiàn)上上千萬(wàn)數(shù)據(jù)量數(shù)據(jù)存在問(wèn)題,為了修復(fù)數(shù)據(jù),通過(guò) Python 腳本進(jìn)行修改
知識(shí)點(diǎn)
Python3、線(xiàn)程池、pymysql、CSV 文件操作、requests
拓展
當(dāng)我們程序在使用到線(xiàn)程、進(jìn)程或協(xié)程的時(shí)候,以下三個(gè)知識(shí)點(diǎn)可以先做個(gè)基本認(rèn)知
CPU 密集型、IO 密集型、GIL 全局解釋器鎖
庫(kù)
pip3 install requests
pip3 install pymysql
流程
實(shí)現(xiàn)代碼
# -*- coding:utf-8 -*-
# @FileName:grade_update.py
# @Desc :在一臺(tái)超級(jí)計(jì)算機(jī)上運(yùn)行過(guò)的牛逼Python代碼
import time
from concurrent.futures import ThreadPoolExecutor,FIRST_COMPLETED,wait
import requests
import pymysql
from projectPath import path
gradeId = [4303, 4304, 1000926, 1000927]
def writ_mysql():
"""
數(shù)據(jù)庫(kù)連接
"""
return pymysql.connect(host="localhost",
port=3306,
user="admin",
password="admin",
database="test"
)
def oprationdb(grade_id, member_id):
"""
操作數(shù)據(jù)庫(kù)
"""
db = writ_mysql()
try:
cursor = db.cursor()
sql = f"UPDATE `t_m_member_grade` SET `current_grade_id`={grade_id}, `modified` =now() WHERE `member_id`={member_id};"
cursor.execute(sql)
db.commit()
print(f"提交的SQL->{sql}")
except pymysql.Error as e:
db.rollback()
print("DB數(shù)據(jù)庫(kù)異常:", e)
db.close()
return True
def interface(rows, thead):
"""
調(diào)用第三方接口
"""
print(f"處理數(shù)據(jù)行數(shù)--->{thead}----數(shù)據(jù)--->{rows}")
try:
url = "http://xxxx/api/xxx-data/Tmall/bindQuery"
body = {
"nickname": str(rows[0]),
"seller_name": "test",
"mobile": "111"
}
heade={"Content-Type": "application/x-www-form-urlencoded"}
res = requests.post(url=url, data=body,headers=heade)
result = res.json()
if result["data"]["status"] in [1, 2]:
grade = result["data"]["member"]["level"]
grade_id = gradeId[grade]
oprationdb(grade_id=grade_id, member_id=rows[1])
return True
return True
except Exception as e:
print(f"調(diào)用異常:{e}")
def read_csv():
import csv
# db = writ_mysql()
#線(xiàn)程數(shù)
MAX_WORKERS=5
with ThreadPoolExecutor(MAX_WORKERS) as pool:
with open(path + '/file/result2_colu.csv', 'r', newline='', encoding='utf-8') as f:
#set() 函數(shù)創(chuàng)建無(wú)序不重復(fù)元素集
seq_notdone = set()
seq_done = set()
# 使用csv的reader()方法,創(chuàng)建一個(gè)reader對(duì)象
reader = csv.reader(f)
n = 0
for row in reader:
n += 1
# 遍歷reader對(duì)象的每一行
try:
seq_notdone.add(pool.submit(interface, rows=row, thead=n))
if len(seq_notdone) >= MAX_WORKERS:
#FIRST_COMPLETED文檔說(shuō)明 -- Return when any future finishes or is cancelled.
done, seq_notdone = wait(seq_notdone,return_when=FIRST_COMPLETED)
seq_done.update(done)
except Exception as e:
print(f"解析結(jié)果出錯(cuò):{e}")
# db.close()
return "完成"
if __name__ == '__main__':
read_csv()
解釋
引入線(xiàn)程池庫(kù)
from concurrent.futures import ThreadPoolExecutor,FIRST_COMPLETED,wait
pool.submit(interface, rows=row, thead=n)
提交任務(wù),interface 調(diào)用的函數(shù),rows、thead 為 interface() 函數(shù)的入?yún)?/p>
任務(wù)持續(xù)提交,線(xiàn)程池通過(guò) MAX_WORKERS 定義的線(xiàn)程數(shù)持續(xù)消費(fèi)
說(shuō)明像這種 I/O 密集型的操作腳本適合使用多線(xiàn)程,如果是 CPU 密集型建議使用進(jìn)行,根據(jù)機(jī)器核數(shù)進(jìn)行配置
原文鏈接:https://testerhome.com/topics/33050
相關(guān)推薦
- 2022-09-04 Apache?Kafka?分區(qū)重分配的實(shí)現(xiàn)原理解析_Linux
- 2022-09-06 React父組件調(diào)用子組件中的方法實(shí)例詳解_React
- 2022-05-23 Jenkins實(shí)現(xiàn)集群化管理以及流水線(xiàn)項(xiàng)目配置_nginx
- 2022-03-26 android獲取及監(jiān)聽(tīng)手機(jī)網(wǎng)絡(luò)狀態(tài)_Android
- 2022-07-08 go語(yǔ)言代碼生成器code?generator使用示例介紹_Golang
- 2022-05-18 C語(yǔ)言自定義類(lèi)型超詳細(xì)梳理之結(jié)構(gòu)體?枚舉?聯(lián)合體_C 語(yǔ)言
- 2023-07-14 react封裝一個(gè)router6
- 2022-03-15 pycharm安裝opencv出現(xiàn)錯(cuò)誤:Could not find a version that
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支