django admin后台中进行多个手机号解密消耗时间对比

需求:
1 手机号在数据库中是使用rsa方式加密存储,后台查看中需要转换为明文,因为需要解密多个手机号,所以在后台查看中消耗时间3秒,希望通过多线程,多进程,异步方式来缩短时间

相关注意点:
Django遵循单请求模型,其中每个请求都在单个线程中处理。在Django的请求 / 响应周期中引入多线程可能无法提供预期的性能提升
据库访问是一个常见的瓶颈,如果数据库连接池不是线程安全的,或者数据库服务器本身无法有效地处理并发连接,则引入多线程可能没有好处。

1:使用异步方式 进行手机号解密–消耗时间1秒

但是,在后台中无法显示手机号

2:使用多线程进行手机号进行解密,消耗时间3秒

3使用多进程来进行手机号解密–直接报错

额,我技术差

4:普通调用对手机号进行解密:消耗3秒

结论:普通调用就好,不用多线程,多进程,异步了

django admin后台中进行多个手机号解密消耗时间对比_第1张图片
django admin后台中进行多个手机号解密消耗时间对比_第2张图片

django admin后台中进行多个手机号解密消耗时间对比_第3张图片

django admin后台中进行多个手机号解密消耗时间对比_第4张图片

1:使用异步方式 进行手机号解密–消耗时间1秒
但是,在后台中无法显示手机号

    # -------------------------------------------------------------------------------------
    # 手机号解密
    # 使用异步方式



    async def decrypt_data_async(self, data):
        # 读取私钥文件
        private_key="""-----BEGIN RSA PRIVATE KEY-----
ekDfPc/BqzRSIkACEijwdnf7NhQveCAiE+aj5NiGkwS/zjX9S96v0qK5SFil6y+c
EXv1GMN54aCmiHWBGq86tOKjV9M4hnlVpuRJPeHi52nAyHpJfmB7
-----END RSA PRIVATE KEY-----"""
        key = serialization.load_pem_private_key(private_key.encode(), password=None, backend=default_backend())
        decrypted_data = key.decrypt(data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                                    algorithm=hashes.SHA256(), label=None)).decode('utf-8')
        return decrypted_data


    async def get_shoujihao(self):
        if len(self.shoujihao) >= 20:
            shoujihao1 = self.shoujihao
            shoujihao1 = base64.b64decode(shoujihao1)
            # Split the data into chunks for parallel decryption
            chunk_size = 8000  # Adjust the chunk size based on your data
            chunks = [shoujihao1[i:i + chunk_size] for i in range(0, len(shoujihao1), chunk_size)]
            # Use asyncio.gather to concurrently decrypt chunks
            decrypted_chunks = await asyncio.gather(*(self.decrypt_data_async(chunk) for chunk in chunks))
            # Concatenate the decrypted chunks
            decrypted_data = ''.join(decrypted_chunks)
            color_code = 'green'
            return format_html('{}', color_code, decrypted_data)
        else:
            color_code = 'green'
            return format_html('-', color_code, )

    get_shoujihao.short_description = '手机号'

    # -------------------------------------------------------------------------------------

2:使用多线程进行手机号进行解密,消耗时间3秒

# --------------------------------------------------------------------------------------
# 使用多线程进行解密
from concurrent.futures import ThreadPoolExecutor
# --------------------------------------------------------------------------------------
    # -------------------------------------------------------------------------------------
    # 手机号解密
    # 使用了多线程方式去进行解密
    def get_shoujihao(self):
        # 1:获取到数据库中的字符串 a
        # 2:把字符串转换成字节类型 b
        # 3:对字节b进行解密为 c
        # 4:返回c
        if len(self.shoujihao)>=20:
            shoujihao1=self.shoujihao
            shoujihao1 = base64.b64decode(shoujihao1)

            # 读取私钥文件
            private_key="""-----BEGIN RSA PRIVATE KEY-----
ekDfPc/BqzRSIkACEijwdnf7NhQveCAiE+aj5NiGkwS/zjX9S96v0qK5SFil6y+c
EXv1GMN54aCmiHWBGq86tOKjV9M4hnlVpuRJPeHi52nAyHpJfmB7
-----END RSA PRIVATE KEY-----"""
            key = serialization.load_pem_private_key(private_key.encode(), password=None, backend=default_backend())
            def decrypt_data(data):
                return key.decrypt(data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                                      algorithm=hashes.SHA256(), label=None)).decode('utf-8')
            # 将数据拆分为块以进行并行解密
            chunk_size = 1000  # 根据数据调整区块大小
            chunks = [shoujihao1[i:i + chunk_size] for i in range(0, len(shoujihao1), chunk_size)]

            # 使用 ThreadPoolExecutor 进行并行解密
            with ThreadPoolExecutor() as executor:
                decrypted_chunks = list(executor.map(decrypt_data, chunks))

            # 连接解密的块
            decrypted_data = ''.join(decrypted_chunks)

            color_code = 'green'
            return format_html('{}', color_code, decrypted_data)

        else:
            color_code = 'green'
            return format_html('-', color_code, )

    get_shoujihao.short_description = '手机号'

    # -------------------------------------------------------------------------------------

3使用多进程来进行手机号解密–直接报错,额,我技术差

# --------------------------------------------------------------------------------------
# 使用多进程进行解密
import logging
from concurrent.futures import ProcessPoolExecutor

logger = logging.getLogger(__name__)
# --------------------------------------------------------------------------------------
    # -------------------------------------------------------------------------------------
    # 手机号解密
    # 使用了多进程方式去进行解密



    def decrypt_data(self, data):
        try:
            # 读取私钥文件
            private_key="""-----BEGIN RSA PRIVATE KEY-----
ekDfPc/BqzRSIkACEijwdnf7NhQveCAiE+aj5NiGkwS/zjX9S96v0qK5SFil6y+c
EXv1GMN54aCmiHWBGq86tOKjV9M4hnlVpuRJPeHi52nAyHpJfmB7
-----END RSA PRIVATE KEY-----"""
            key = serialization.load_pem_private_key(private_key.encode(), password=None, backend=default_backend())
            return key.decrypt(data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                              algorithm=hashes.SHA256(), label=None)).decode('utf-8')
        except Exception as e:
            logger.error(f"Error in decryption: {e}")
            raise
    def get_shoujihao(self):
        if len(self.shoujihao) >= 20:
            shoujihao1 = self.shoujihao
            shoujihao1 = base64.b64decode(shoujihao1)

            # 将数据拆分为块以进行并行解密
            chunk_size = 1000  # 根据数据调整区块大小
            chunks = [shoujihao1[i:i + chunk_size] for i in range(0, len(shoujihao1), chunk_size)]

            # 使用 ProcessPoolExecutor 进行并行解密
            with ProcessPoolExecutor(max_workers=2) as executor:
                decrypted_chunks = list(executor.map(self.decrypt_data, chunks))

            # 连接解密的块
            decrypted_data = ''.join(decrypted_chunks)

            color_code = 'green'
            return format_html('{}', color_code, decrypted_data)
        else:
            color_code = 'green'
            return format_html('-', color_code, )

    get_shoujihao.short_description = '手机号'

    # -------------------------------------------------------------------------------------

4:普通调用对手机号进行解密:消耗3秒

    # -------------------------------------------------------------------------------------
    # 手机号解密
    def get_shoujihao(self):
        # 1:获取到数据库中的字符串 a
        # 2:把字符串转换成字节类型 b
        # 3:对字节b进行解密为 c
        # 4:返回c
        if len(self.shoujihao)>=20:
            shoujihao1=self.shoujihao
            shoujihao1 = base64.b64decode(shoujihao1)

            # 读取私钥文件
            private_key="""-----BEGIN RSA PRIVATE KEY-----
ekDfPc/BqzRSIkACEijwdnf7NhQveCAiE+aj5NiGkwS/zjX9S96v0qK5SFil6y+c
EXv1GMN54aCmiHWBGq86tOKjV9M4hnlVpuRJPeHi52nAyHpJfmB7
-----END RSA PRIVATE KEY-----"""
            key = serialization.load_pem_private_key(private_key.encode(), password=None, backend=default_backend())
            decrypted_data = key.decrypt(shoujihao1, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                                                      algorithm=hashes.SHA256(), label=None))
            # decrypted_data 的类型为字节
            decrypted_data=decrypted_data.decode('utf-8')
            # decrypted_data.decode()之后的类型为字符串
            shoujihao1=decrypted_data
            # print("类型")
            # print(type(decrypted_data))
            # print(decrypted_data)

            # 打印解密后的消息
            color_code = 'green'
            return format_html('{}', color_code, shoujihao1)
        else:
            color_code = 'green'
            return format_html('-', color_code, )

    get_shoujihao.short_description = '手机号'

    # -------------------------------------------------------------------------------------

你可能感兴趣的:(django,数据库,sqlite)