使用递归替换参数${变量}


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Project: py-gql-fast-test-api
@File: handle.py
@Author: zy7y
@Time: 2021/3/31 16:48
@Blog: https://www.cnblogs.com/zy7y
@Github: https://gitee.com/zy7y
@Desc: 处理方法
"""


class Handle:
    var_pool = {}

    @staticmethod
    def set_var(key: object, value: object):
        """存变量"""
        Handle.var_pool[key] = value

    @staticmethod
    def get_var(key: object, default: object = None):
        """取变量"""
        return Handle.var_pool.get(key, object)

    @staticmethod
    def handle_var_list(value: list):
        """
        处理参数替换~ 类型是list的逻辑
        """
        for index, liv in enumerate(value):
            if isinstance(liv, str) and liv[:2] == '${' and liv[-1] == '}':
                # 获得key部分内容
                liv = liv[2:-1]
                # 取到key对应的value,复制给当前下标
                value[index] = Handle.get_var(liv)
            elif isinstance(liv, list):
                # 如果 子元素还是 list 就再迭代list
                Handle.handle_var_list(liv)
            elif isinstance(liv, dict):
                # 如果子元素是 dict 就再迭代字典
                Handle.handle_var(liv)

    @staticmethod
    def handle_var(var: dict) -> dict:
        """处理自定义参数类型"""
        for key, value in var.items():
            # 如果是字典就 迭代字典
            if isinstance(value, dict):
                Handle.handle_var(value)
            # 如果是list 就迭代list, 递归 list处理方法
            elif isinstance(value, list):
                Handle.handle_var_list(value)
            # 如果是str 就替换
            elif isinstance(value, str) and value[:2] == '${' and value[-1] == '}':
                # 获得key部分内容
                value = value[2:-1]
                # 取到key对应的value
                var[key] = Handle.get_var(value)
        return var


if __name__ == '__main__':

    Handle.var_pool = {"name": "att", "age": 18, "height": 17.8}
    # 需要处理的字典
    data = {
        #  字典 提取
        "name": "${name}",
        # 字典嵌套字典提取
        "info": {"${name}": ["${age}", "${height}"]},
            "lists": ["${name}", ["${age}", "${height}"], {"name": "${name}"}]

    }
    print(Handle.handle_var(data))

可能有Bug

上一篇:Linux下查看CPU型号,内存大小,硬盘空间的命令(详解)


下一篇:课程设计扫雷