首页 > 编程语言 >python多线程修改共享全局变量不安全

python多线程修改共享全局变量不安全

时间:2022-12-17 10:11:43浏览次数:55  
标签:index account 全局变量 python self auth auths 多线程 response

当需要对全局变量进行更改时,则会出现不安全的情况

 

# -*- 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

相关文章

  • 第十四章《多线程》第8节:线程池
    系统启动一个线程的成本是比较高的,因为启动线程的操作要与操作系统交互。如果程序中需要创建大量生存期较短的线程,那么使用线程池将会大幅度提高程序的运行效率。线程池中保......
  • 第十四章《多线程》第9节:ThreadLocal类
    如果多个线程共用一个对象,那么这个对象的属性值对于这些线程都是相同的。例如有一个a对象,它有一个x属性,如果x属性的值是1,那么对于任何一个线程而言,a对象的x属性都是1。但有......
  • 第十四章《多线程》第7节:线程组
    多个线程可以组成一个线程组,线程组可以对一批线程统一调度和管理,也就是说,控制一个线程组相当于控制这个线程组中所有的线程。Java语言以ThreadGroup这个类来表示线程组这个......
  • 第十四章《多线程》第6节:线程通信
    之前所有的例子中,线程的执行都具有一定的随机性。如果希望线程能够有序的执行,必须使用线程通信技术。Java语言提供了一些线程通信的机制能够保证线程的有序执行,本小节将详细......
  • 第十四章《多线程》第4节:控制线程
    从14.3小节所列举的各个例子可以很明显的看出:线程的执行有一定的随机性,如果不加以适当控制,会导致执行结果的不确定性。实际开发过程中,很多情况下都需要让线程按照程序员期望......
  • Python学习笔记--判断语句的延续
    ifelse语句示例:需要注意的是,if后面必须有条件,而else后面可以不需要判断条件案例:实现:ifelifelse语句多条件判断,if和elif后面必须有条件,else后面可以没有......
  • Python爬虫实现:三连文章参与抽奖
    ......
  • Python技能树丨Python简介
    ......
  • python学习笔记整理04(面向对象)
     1.概念2.编写步骤3.魔法方法4.封装5.私有和公有6.继承7.重写8.多态9.属性和方法  1.概念  2.编写步骤#1.创建类#用class关键字定义类,类名用大......
  • python-异常
    '''异常程序出现异常错误情况有两种编码报错-不符合语言的语法运行报错--异常程序运行气节时要避免异常的程序一旦出现异常就会终止......