Business_rules 引擎
Business_rules 规则引擎介绍:规则引擎可以把业务规则从代码里抽离出来,让规则可以独立配置、独立管理、独立扩展,而不用频繁改代码。简单来说可以代替代码中大量的 if-else,如果项目中包含大量的定制化需求,导致代码含有大量 if-else,可以使用规则引擎优化,实现热插拔,业务逻辑更加清晰。
Business_rules 源码:venmo/business-rules: Python DSL for setting up business intelligence rules that can be configured without code
优点:可以定义动作类,满足规则后直接执行对应的动作。虽然源码中支持的数据类型和 Operation 很少,但是可以通过修改源码增加数据类型以及 Operation。
缺点:
- 源码中 Operation 类型较少
- 需要定义变量类,变量的类型少,只有数字,字符串以及布尔类型
Business_rules 规则引擎开发流程
- 定义变量集合(在规则中可以引用到集合中的数据)
- 定义 action 集合(满足规则条件后,执行的 action 集合)
- 添加规则(本文使用 yaml 配置文件添加规则)
- 运行规则引擎
Variable Types
| Variable Types | 解释 | Operation |
|---|---|---|
| @numeric_rule_variable | 整数、浮点数 | equal_to, greater_than, less_than, greater_than_or_equal_to, less_than_or_equal_to |
| @string_rule_variable | Python 字符串,Unicode 字符串 | equal_to, not_equal_to, starts_with, ends_with, contains, matches_regex, non_empty |
| @boolean_rule_variable | 布尔值 | is_true, is_false |
| @select_rule_variable | 集合/列表 - 单选 | contains, does_not_contain |
| @select_multiple_rule_variable | 集合/列表 - 多选 | contains_all, is_contained_by, shares_at_least_one_element_with, shares_exactly_one_element_with, shares_no_elements_with |
| @list_rule_variable | 列表 - 修改源码 | is_in, is_not_in |
定义变量集合
变量代表系统中的值,通常是某个特定对象的值。通过设置阈值条件来创建规则,这样当计算出触发该条件的变量时,会采取某个动作。
class ProductVariables(BaseVariables):
def __init__(self, product):
self.product = product
@numeric_rule_variable
def ():
.product.current_inventory
():
last_order = .product.orders[-]
(last_order.expiration_date - datetime.date.today()).days
():
datetime.datetime.now().strftime()
():
products.related_products

