首页 > 编程语言 >python 线程池使用

python 线程池使用

时间:2023-05-18 11:33:58浏览次数:49  
标签:__ name python self list cursor html 线程 使用

代码应用场景:需要对数据库中的数据进行批量查询,然后将查询到的结果每条分别写入不同的文本文件中。由于数据数量较多,考虑使用线程池减少时间开销。

#核心代码逻辑
import pymysql
from dbutils.pooled_db import PooledDB
import threading
class processing:
    def __init__(self,maxconnections=5,thread_num=20,host,user,password,db_name):
        """创建数据库连接池
        """
        #数据库连接信息
        self.pool =PooledDB(creator=pymysql,maxconnections=maxconnections,maxshared=maxconnections,host=host,user=user,passwd=password,db=db_name,port=3306,charset='utf8mb4',blocking=False)
    #每个线程运行:从数据库读取一条数据,写入一个文件中
    def threading_doing(self,html):
        #从数据库获取数据
        conn = self.pool.connection()
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        #html_list = html_list.replace('"',"").split(",")
        cursor.execute("select content from table_name where html = %s",(html,))
        #对查询到的数据格式做处理
        html_content = cursor.fetchall()[0]["content"]
        #写入文件
        file_name = html.replace("http://","").replace(":","_")
        with open(f"tmp_2/htmls/{file_name}.txt","w+",encoding="utf-8") as f:
            f.write(html_content)
        return file_name
        #关闭链接
        cursor.close()
        conn.close()
    def run(self):
        start_time = datetime.datetime.now()
        print(f"开始时间:{start_time.strftime('%Y%m%d%H%M%S')}")
        # 查找表中全部数据
        conn = self.pool.connection()
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cursor.execute("select target from tabel_name where simple_number > 9")
        target_list_all = cursor.fetchall()
        cursor.close()
        conn.close()
        for i in target_list_all:
            target_list = json.loads(i["target"])
            #线程池使用核心代码
            with ThreadPoolExecutor(max_workers=100) as t:
                obj_list = []
                for html in target_list:
                    obj = t.submit(self.threading_doing,html)
                    obj_list.append(obj)
                for future in as_completed(obj_list):
                    data = future.result()
                    print(data)
        end_time = datetime.datetime.now()
        print('{} 完成!耗时:{} '.format(end_time.strftime('%Y%m%d%H%M%S'),end_time-start_time))
if __name__ == "__main__":
    p = processing("")
    p.run()

 

标签:__,name,python,self,list,cursor,html,线程,使用
From: https://www.cnblogs.com/Iitt1evegbird/p/17411419.html

相关文章

  • 前端工作小结1-拦截器的使用
    1.拦截器综述拦截器的功能是定义在Java拦截器规范。拦截器规范定义了三种拦截点:业务方法拦截,生命周期回调侦听,超时拦截(EJB)方法。在容器的生命周期中进行拦截   publicclassDependencyInjectionInterceptor{      @PostConstruct      publicvoidi......
  • Java系列 | IntelliJ IDEA 如何导入和使用一个Jar包
    第一步:创建lib文件创建lib文件,统一管理导入的jar包(若已有lib文件,则直接可以进行第二步)文件名称命名为`lib`第二步:对lib文件建立依赖选择【File】→【ProjectStructure…】 在弹出的页面中选择【Modules】再选择此项目,点击右边的【Dependencies】,再选择下面的小加号,选择......
  • python 性能测试之获取app fps
    一、功能描述该脚本主要是获取视频/语音通话、语音房、看视频等app的fps 二、代码实现importos,csvimporttimeimportnumpyasnpfrommatplotlibimportpyplotaspltfromsubprocessimportPopen,PIPEfromcheck_packageimportcheck_packageimportmath......
  • python基础学习-发送邮件
    importsmtplibfromemail.headerimportHeaderfromemail.mime.multipartimportMIMEMultipartfromemail.mime.textimportMIMEText"""发送普通邮件"""#创建邮件主体对象email=MIMEMultipart()#设置发件人、收件人和主题email['From']=&#......
  • Python程序与用户交互&基本运算符
    一、用户交互1.输入input:关键字:input()-输入在python3中input关键字会等待用户的输入,用户输入任何内容,都存成字符串类型,然后赋值给等号左边的变量名在python2中存在一个raw_input功能与python3中的input功能一模一样在python2中还存在一个input功能,需要用户输入一个明......
  • web自动化测试入门篇04——selenium+python基础方法封装
      ......
  • python - 单例模式
    Python中的单例单例模式(Singletonpattern),是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的一个类只有一个实例。即一个类只有一个对象实例。Python中实现单例的几种方法:使用模块使用函数装饰器使用类装饰器......
  • 使用eNSP模拟器配置GVRP(以Normal模式为例)
    知识点讲解:什么是GVRP?答:GARP(GenericAttributeRegistrationProtocol)协议主要用于建立一种属性传递扩散的机制,以保证协议实体能够注册和注销该属性。GARP作为一个属性注册协议的载体,可以用来传播属性。将GARP协议报文的内容映射成不同的属性即可支持不同上层协议应用。GVRP(GARP......
  • Redis 高级特性 Redis Stream使用
    RedisStream简介RedisStream是Redis5.0版本新增加的数据结构。Stream从字面上看是流类型,但其实从功能上看,应该是Redis对消息队列(MQ,MessageQueue)的完善实现。下文称Stream为队列Stream出现原因:Stream的出现是为了给Redis提供完善的消息队列功能基于Reids的消息队列......
  • OpenFileDialog的使用实例
    'DimexcelFolderPathAsString=""'DimopenFileDialog1AsNewOpenFileDialog()'openFileDialog1.Filter="ExcelFiles|*.xlsx;*.xls"'openFileDialog1.Title="SelectExcelFile"......