当需要对全局变量进行更改时,则会出现不安全的情况
# -*- coding: utf-8 -*- """================================================================================================================ @date : 2022/8/17 16:06 @function : 自动转发 ================================================================================================================""" import json import time import requests from loguru import logger from datetime import datetime from concurrent.futures import ThreadPoolExecutor from utils.common import open_gsheet class AUTO_TRANSFER_CHAT: def __init__(self): self.headers = { 'accept': '*/*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9', 'authorization': '', 'content-type': 'text/plain;charset=UTF-8', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36', } self.shop_id_dict = { '476792408':'CO' } def get_auths(self): """获取在线客服""" sheet = open_gsheet('L.OP3.3-Mass Outbound Chat Tool', 'Online status') datas = sheet.get_values('A2:E') account_auths = [] for data in datas: account_auths.append((data[0].strip(), data[4].strip())) logger.info(f'account_auths: {len(account_auths)}, {account_auths[:5]}') return account_auths def _request_get(self, url, account): i = 0 while i < 3: try: response = requests.get(url, headers=self.headers, timeout=30) response = response.json() return response except Exception as e: i += 1 print(f'try {i} times, {account} {e.args}') else: raise Exception(f'{account} request error') def _request_put(self, url, payload, to_name): i = 0 while i < 3: try: response = requests.put(url, data=json.dumps(payload), headers=self.headers, timeout=30) return response except: i += 1 print(f'try {i} times, {to_name}') else: raise Exception(f'{to_name} transfer error') def get_all_unread(self, account_auth, index, l): account, auth = account_auth[0], account_auth[1] url = 'https://xxx/webchat/api/v1.2/subaccount/conversations?direction=older&_s=1&type=unread' self.headers['authorization'] = auth + account # 多线程更改全局变量不安全!这里的authorization和account不一定和outbound_receive201相同 if account == 'outbound_receive201': print(account, self.headers) response = self._request_get(url, account) try: conversations = [(i['id'], i['shop_id'], i['to_id'], i['to_name']) for i in response] except: raise Exception(response) logger.info(f'{index}/{l} {account}, conversations: {len(conversations)}, {conversations}') return conversations def parse_exception(self, obj): result = obj.result() if result: print(result) def treat_one_account_unit(self, account_auth, index, l): account, auth = account_auth[0], account_auth[1] th_timestamp = int(time.mktime(time.strptime((datetime.now()).strftime('%Y-%m-%d') + ' 10:30:00', '%Y-%m-%d %H:%M:%S'))) vn_timestamp = int(time.mktime(time.strptime((datetime.now()).strftime('%Y-%m-%d') + ' 08:30:00', '%Y-%m-%d %H:%M:%S'))) now = time.time() if (now > th_timestamp) or (now > vn_timestamp and 'agentvncb' in account) or 'outbound_receive' in account: pass else: return self.get_all_unread(account_auth, index, l) def treat_one_account(self, index, l, account_auth): logger.info(f'{index}/{l} {account_auth[:2]}') self.treat_one_account_unit(account_auth, index, l) def main(self):
account_auths = [] exector = ThreadPoolExecutor(max_workers=10) for index, account_auth in enumerate(account_auths): if index < 0: continue exector.submit(self.treat_one_account, index, len(account_auths), account_auth).add_done_callback(self.parse_exception) exector.shutdown(wait=True) if __name__ == '__main__': a = AUTO_TRANSFER_CHAT() a.main()
改进措施:不直接修改全局变量:
header = self.headers.copy() header['authorization'] = auth + account
标签:index,account,全局变量,python,self,auth,auths,多线程,response From: https://www.cnblogs.com/crawler-king/p/16988641.html