import pymysql from pymysql.cursors import DictCursor from multiprocessing import cpu_count from update.models import Cinema import queue import threading from django.utils import timezone import datetime class GetVersion(object): def __init__(self, cinema_ip_list=None): self.cinema_ip_list = cinema_ip_list self.queue = queue.Queue() # 注册队列 self.th_num = 0 # 获取CPU核心数量,-1后座位处理逻辑的线程数量 def get_all_cinema(self): print('get_all_cinema') if self.cinema_ip_list is None: all_cinema_obj = Cinema.objects.all() else: all_cinema_obj = Cinema.objects.filter(ip__in=self.cinema_ip_list) for cinema_obj in all_cinema_obj: print(cinema_obj) data = { 'ip': cinema_obj.ip, 'db_user': cinema_obj.db_user, 'db_pwd': cinema_obj.db_pwd } self.queue.put(data) cpu_num = cpu_count() - 1 if cpu_count() > 1 else 1 cinema_num = len(all_cinema_obj) self.th_num = cpu_num if cpu_num < cinema_num else cinema_num def main_process(self): print('main_process') self.get_all_cinema() while self.queue.qsize() > 0: threads = [] for i in range(self.th_num): t = threading.Thread(target=self.get_cinema_ver, args=(self.queue,)) threads.append(t) for i in range(self.th_num): threads[i].start() for i in range(self.th_num): threads[i].join() @staticmethod def get_cinema_ver(q): if q.empty(): return else: cinema_config = q.get() sql_str = "SELECT * FROM cinema_version;" ip = cinema_config.get('ip') db_config = { 'host': ip, 'user': cinema_config.get('db_user'), 'password': cinema_config.get('db_pwd'), 'database': 'cine', 'connect_timeout': 5, } db_conn = pymysql.Connect(**db_config) db_cursor = db_conn.cursor(cursor=DictCursor) db_cursor.execute(sql_str) res = db_cursor.fetchone() update_data = { 'sys_ver': res['server_version'], 'client_ver': res['client_version'], # 'update_time': datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') 'update_time': timezone.now() } print(ip, update_data, db_config) cinema_obj = Cinema.objects.filter(ip=ip).update(**update_data) if __name__ == '__main__': v = GetVersion() v.get_all_cinema()