wildcard_compare.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # coding=utf-8
  2. """
  3. @project: maxkb
  4. @Author:wangliang181230
  5. @file: wildcard_compare.py
  6. @date:2026/3/30 12:11
  7. @desc:
  8. """
  9. import fnmatch
  10. import re
  11. from typing import List
  12. from application.flow.compare import Compare
  13. from common.cache.mem_cache import MemCache
  14. match_cache = MemCache('wildcard_to_regex', {
  15. 'TIMEOUT': 3600, # 缓存有效期为 1 小时
  16. 'OPTIONS': {
  17. 'MAX_ENTRIES': 500, # 最多缓存 500 个条目
  18. 'CULL_FREQUENCY': 10, # 达到上限时,删除约 1/10 的缓存
  19. },
  20. })
  21. def translate_and_compile_and_cache(wildcard):
  22. match = match_cache.get(wildcard)
  23. if not match:
  24. regex = fnmatch.translate(wildcard)
  25. match = re.compile(regex).match
  26. match_cache.set(wildcard, match)
  27. return match
  28. class WildcardCompare(Compare):
  29. def support(self, node_id, fields: List[str], source_value, compare, target_value):
  30. if compare == 'wildcard':
  31. return True
  32. def compare(self, source_value, compare, target_value):
  33. # 转成正则,性能更高
  34. match = translate_and_compile_and_cache(str(target_value))
  35. return bool(match(str(source_value)))