dbt modules 宏简单说明

发布时间 2023-08-08 23:07:19作者: 荣锋亮

dbt modules 宏提供了让dbt 访问python 包的能力,处理上基于了jinja 的上下问处理,但是目前官方没有完整暴露此方法
核心还是因为安全问题,只提供了一些时间、正则、迭代处理的,实际使用上基于了python 模块的动态加载(getattr)

modules 宏的使用参考 

{% set now = modules.datetime.datetime.now() %}
{% set three_days_ago_iso = (now - modules.datetime.timedelta(3)).isoformat() %}

modules 上下文

  • 定义
def get_context_modules() -> Dict[str, Dict[str, Any]]:  
    return {                                             
        "pytz": get_pytz_module_context(),               
        "datetime": get_datetime_module_context(),       
        "re": get_re_module_context(),                   
        "itertools": get_itertools_module_context(),     
    }                                                    
  • 加载
def get_datetime_module_context() -> Dict[str, Any]:                       
    context_exports = ["date", "datetime", "time", "timedelta", "tzinfo"]  
 
    return {name: getattr(datetime, name) for name in context_exports}                                                                                
说明

dbt 有不少需要时间以及正则处理的就使用了此模块提供的能力

参考资料

core/dbt/context/base.py
https://docs.getdbt.com/reference/dbt-jinja-functions/modules