基类,用于轻松筛选字典的iterable。
AnyFilter的Python项目详细描述
anyfilter是定义数据过滤器的简单基类。它提供了 以下功能:
- 以json格式存储配置
- 使用用户信息和时间戳保留以前版本的配置
- 隔离自定义代码
其目的是在任何情况下创建Filter类的子类 必须编写代码。这使得自定义代码不在主代码中 工作流和代码库,并允许插入和切换Filter子类 根据需要,同时将过滤器的配置存储在代码库之外 以及应用程序的主要数据库,以便于移植和维护。
动机
导致这种解决方案的问题是需要从 最终用户。通常,尤其是当用户是客户机时,这些数据可以 不依赖于满足系统的输入规范。
这通常会导致这些次优解之一:
- 使用自定义脚本预处理每个客户端的数据
- 向核心产品添加一堆if语句或其他类似逻辑
- 试图使转换脚本具有足够的通用性以供重用,因此 使它们在主要用途上不那么有用,也更难调试
- 将数据硬编码为转换脚本
通常每个客户机或项目都有一个自定义转换, 因此,这些解决方案的可伸缩性不好。
anyfilter的目标是:
- 最小化主代码库中的自定义代码量
- 以可移植格式将配置存储在应用程序数据库之外
- 允许在不部署代码的情况下更新配置数据(特权用户 甚至可以通过某种gui编辑配置)
优点
- 创建可插入的数据筛选器
- 将配置存储在应用程序数据库之外
- 轻松备份和恢复配置
- 跨服务器轻松复制配置
计划功能
- 导出和导入配置
- 将配置转换为HTML表单和从HTML表单转换为易于使用的前端功能
- 轻松恢复到以前的配置
- 综合单元测试
示例用法
#!/usr/bin/env python""" This is a simple example of the use of the Filter class. In this case, a dictionary has some keys renamed. This is a trivial example; filters can be as complex as required. """fromanyfilterimportFilterclassNameFilter(Filter):""" A filter that changes the names of dictionary keys. 'data' should be an iterable of dictionaries """def__call__(self,data):""" The contents of this function are the least-important part of this demo. This is where you custom code will go, doing whatever it is you need with whatever config format and content you need. """forrecindata:# The config for this filter is a dictionary where the# key is the key name to replace, and the value is the new name.# update values in "data" dictforkey,valueinself.config.items():ifkeyinrec:rec[value]=rec[key]delrec[key]returndataif__name__=='__main__':importos# for dealing with the environment variable manually# set environment variable for demo purposesoriginal_envvar=os.environ.get('FILTER_CONFIG_DIR','')os.environ['FILTER_CONFIG_DIR']='/tmp'# Instantiate subclass. The only argument is the uid of the subject# of the filter. For example, if you need to store different rules# per user of your site, you might use the user's primary key here.# This allows storage of configs per filter *and* per user.name_filter=NameFilter('foo')# Set some filter items. This normally won't be a part of the flow.# It's here for demo purposes. In normal usage, the config would# already be set and probably rarely updated.name_filter.config={'dog':'canine','cat':'feline','horse':'equine',}name_filter.save_config(user='example')data=[{'cat':'meow','dog':'woof','horse':'neigh','foo':'bar',}]printdata# originalprintname_filter(data)# altered# Put it back like we found it, just to be good citizens.os.environ['FILTER_CONFIG_DIR']=original_envvar
样本输出
[{'horse': 'neigh', 'foo': 'bar', 'dog': 'woof', 'cat': 'meow'}] [{'equine': 'neigh', 'feline': 'meow', 'canine': 'woof', 'foo': 'bar'}]