ApiFrame--参数替换(2)

前言

我的博客(15 python接口--参数替换)中已写了通过字典替换方式的接口数据处理。
此处引入模板引擎的方法进行参数替换,写法更加简单直接。代码可读性更强。

python template

简介

template是python中的string库的一部分,使用template可以不编辑应用就可以改变其中的数据
文档:https://www.geeksforgeeks.org/template-class-in-python/

Code

 
from string import Template 
  
t = Template('x is $x') 
  
print (t.substitute({'x' : 1})) 
  
>x is 1

Student = [('Ram',90), ('Ankit',78), ('Bob',92)] 
  
t = Template('Hi $name, you have got $marks marks') 
  
for i in Student: 
     print (t.substitute(name = i[0], marks = i[1]))
>
Hi Ram, you have got 90 marks
Hi Ankit, you have got 78 marks
Hi Bob, you have got 92 marks

jinja2

flask等前端常使用模板(略),涉及到模板引擎概念。

mustache-chevron

chevron替代了pystache,官方解释:Chevron 运行时间不到 pystache 的一半
mustache地址:https://mustache.github.io/
chevron地址:https://github.com/noahmorrison/chevron 
通过chevron生成py文件: https://my.oschina.net/u/4626630/blog/4526532
import chevron

res =chevron.render('Hello, {{ hello }}!', {'hello': 'World'})

print(res)

##
args = {
  'template': 'Hello, {{ mustache }}!',

  'data': {
    'mustache': 'World'
  }
}

res1 = chevron.render(**args)

print(res1)

##

args = {
    'template': 'Hello, {{> thing }}!',

    'partials_dict': {
        'thing': 'World'
    }
}


res2 = chevron.render(**args)
print(res2)

## 函数
def param_replace(org_dict, new_dict):
  args = {'template': str(org_dict),'data': new_dict }
  return chevron.render(**args)

嵌套字典查找数值

def find_dict_by_key(self, target_dict, target_key, resp=None):
    """
    嵌套字典中根据key查找值,返回list
    :param target_dict:
    :param target_key:
    :param resp:
    :return: list
    """
    if resp is None:
        resp = []
    if isinstance(target_dict, str) and target_dict.startswith('{') and target_dict.endswith('}'):
        if isinstance(json.loads(target_dict.replace('\'', '\"')), dict):
            target_dict = json.loads(target_dict.replace('\'', '\"'))
    if isinstance(target_dict, (list, tuple)):
        for item in target_dict:
            resp = self.find_dict_by_key(item, target_key, resp)
    if isinstance(target_dict, dict):
        for key, value in target_dict.items():
            if key == target_key:
                resp.append(value)
                resp = self.find_dict_by_key(value, target_key, resp)
            else:
                resp = self.find_dict_by_key(value, target_key, resp)
    return resp
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值