项目中遇到这样的需求,场景需要参数动态的变为属性,将代码弄上来供大家参考
import traceback
TEMPLATE_MARK_BEG = '{{' TEMPLATE_MARK_END = '}}'
def param_to_property(*props, **kwprops): if props and kwprops: raise SyntaxError("Can not set both props and kwprops at the same time.")
class Wrapper(object):
def __init__(self, func): self.func = func self.kwargs, self.args = {}, []
def __getattr__(self, attr): if kwprops: for prop_name, prop_values in kwprops.items(): if attr in prop_values and prop_name not in self.kwargs: self.kwargs[prop_name] = attr return self elif attr in props: self.args.append(attr) return self raise AttributeError("%s parameter is duplicated or not allowed!" % attr)
def __call__(self, *args, **kwargs): if kwprops: kwargs.update(self.kwargs) self.kwargs = {} return self.func(*args, **kwargs) else: new_args, self.args = self.args + list(args), [] return self.func(*new_args, **kwargs) return Wrapper
class TemplateApi(object): def __init__(self): self._get_template_list = [ "login_template", "test_template", "move_template", "replace_template" ]
@property def render_template(self): @param_to_property(template_name=self._get_template_list) def _render_template(template_name, **kwargs): file_name = template_name + '.txt' try: with open(file_name, mode='r') as f: file_content = f.read() str_replace = self._replace_template_mark_with_dict(file_content, kwargs) return self._create_messages(str_replace) except IOError: traceback.print_exc()
return _render_template
def _replace_template_mark_with_dict(self, src_str, replace_dict): str_replace = src_str for k, v in replace_dict.items(): mark_beg = TEMPLATE_MARK_BEG + k default_mark = mark_beg + TEMPLATE_MARK_END mark = TEMPLATE_MARK_BEG + k + '=' replace_value = mark_beg + '=' + v if mark in str_replace: str_replace = self._replace_default_mark_with_value(str_replace, mark, replace_value) if default_mark in str_replace: str_replace = self._replace_mark_with_value(str_replace, default_mark, replace_value) return str_replace
@staticmethod def _replace_mark_with_value(src_str, mark, value): replace_value = value + TEMPLATE_MARK_END return src_str.replace(mark, replace_value)
@staticmethod def _replace_default_mark_with_value(src_str, default_mark, value): beg_index = src_str.find(default_mark, 0, len(src_str)) end_index = src_str.find(TEMPLATE_MARK_END, beg_index, len(src_str)) default_value = src_str[beg_index:end_index] return src_str.replace(default_value, value)
@staticmethod def _create_messages(src_str): str_result = src_str while str_result.find(TEMPLATE_MARK_BEG) != -1: beg_index = str_result.find(TEMPLATE_MARK_BEG, 0, len(src_str)) end_index = str_result.find(TEMPLATE_MARK_END, beg_index, len(src_str)) str_value = str_result[beg_index+2:end_index] if '=' in str_value: value = str_value.split('=')[1] else: value = '' str_result = str_result.replace(TEMPLATE_MARK_BEG + str_value + TEMPLATE_MARK_END, value) return str_result
|