網(wǎng)站首頁 編程語言 正文
背景
由于不同乙方對(duì)服務(wù)商業(yè)務(wù)接口字段理解不一致,導(dǎo)致線上上千萬數(shù)據(jù)量數(shù)據(jù)存在問題,為了修復(fù)數(shù)據(jù),通過 Python 腳本進(jìn)行修改
知識(shí)點(diǎn)
Python3、線程池、pymysql、CSV 文件操作、requests
拓展
當(dāng)我們程序在使用到線程、進(jìn)程或協(xié)程的時(shí)候,以下三個(gè)知識(shí)點(diǎn)可以先做個(gè)基本認(rèn)知
CPU 密集型、IO 密集型、GIL 全局解釋器鎖
庫
pip3 install requests
pip3 install pymysql
流程
實(shí)現(xiàn)代碼
# -*- coding:utf-8 -*-
# @FileName:grade_update.py
# @Desc :在一臺(tái)超級(jí)計(jì)算機(jī)上運(yùn)行過的牛逼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ù)庫連接
"""
return pymysql.connect(host="localhost",
port=3306,
user="admin",
password="admin",
database="test"
)
def oprationdb(grade_id, member_id):
"""
操作數(shù)據(jù)庫
"""
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ù)庫異常:", 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()
#線程數(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)建無序不重復(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文檔說明 -- 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()
解釋
引入線程池庫
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ù)提交,線程池通過 MAX_WORKERS 定義的線程數(shù)持續(xù)消費(fèi)
說明像這種 I/O 密集型的操作腳本適合使用多線程,如果是 CPU 密集型建議使用進(jìn)行,根據(jù)機(jī)器核數(shù)進(jìn)行配置
原文鏈接:https://testerhome.com/topics/33050
相關(guān)推薦
- 2022-11-27 Rust語言中的String和HashMap使用示例詳解_Rust語言
- 2022-04-20 C語言特殊符號(hào)的補(bǔ)充理解_C 語言
- 2022-04-27 前端實(shí)現(xiàn)滑動(dòng)按鈕AJAX與后端交互的示例代碼_AJAX相關(guān)
- 2023-02-05 Python實(shí)現(xiàn)前向和反向自動(dòng)微分的示例代碼_python
- 2022-04-11 python寫入Excel表格的方法詳解_python
- 2022-07-04 python生成單位陣或?qū)顷嚨娜N方式小結(jié)_python
- 2022-05-17 go實(shí)現(xiàn)冒泡排序算法_Golang
- 2022-08-22 C++示例詳解Prim算法與優(yōu)先隊(duì)列_C 語言
- 最近更新
-
- 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)證過濾器
- Spring Security概述快速入門
- 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)程分支