19 python接口--参数替换(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

猜你喜欢

转载自blog.csdn.net/qq_25672165/article/details/109533283