You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache Airflow子项目导入DAG后UI无法显示DAG代码问题

问题原因

Airflow UI的Code标签展示的是DAG对象fileloc属性指向的文件内容。你当前的导入方式中,Airflow会将加载后的DAG关联到你的导入脚本(而非原始DAG文件),所以fileloc指向的是导入脚本路径,导致显示的是导入脚本代码而非DAG本身的代码。

解决方案

方案1:使用Airflow官方多目录扫描(推荐)

Airflow 2.x支持配置多个DAG目录,无需手动写导入脚本:

  1. 打开Airflow配置文件airflow.cfg
  2. 找到dags_folder配置项,将其修改为包含你的两个目录,用逗号分隔:
    dags_folder = /opt/airflow/dags,/opt/airflow/projetos/basevinculos_py,/opt/airflow/projetos/pdi_consulta
    
  3. 重启Airflow Webserver和Scheduler服务
  4. Airflow会自动扫描这些目录下的DAG文件,UI的Code标签将正常显示原始DAG代码

方案2:手动设置DAG的fileloc属性(保留导入脚本的情况下)

如果你必须保留当前的导入脚本,可以在加载DAG时手动指定fileloc为原始DAG文件路径:
修改你的导入脚本如下:

import os
from airflow.models import DagBag
import sys

dags_dirs = [
    '/opt/airflow/projetos/basevinculos_py',
    '/opt/airflow/projetos/pdi_consulta'
]

for dir in dags_dirs:
    sys.path.append(os.path.expanduser(dir))

for dir in dags_dirs:
    dag_bag = DagBag(os.path.expanduser(dir))

    if dag_bag:
        # 建立dag_id到原始文件路径的映射
        dag_file_map = {}
        for file_path, dag_ids_in_file in dag_bag.dag_file_dict.items():
            for dag_id in dag_ids_in_file:
                dag_file_map[dag_id] = file_path
        
        for dag_id, dag in dag_bag.dags.items():
            # 手动设置fileloc为原始DAG文件路径
            dag.fileloc = dag_file_map.get(dag_id, dag.fileloc)
            globals()[dag_id] = dag

修改后重启Airflow服务,UI的Code标签将显示对应DAG的原始代码。

内容的提问来源于stack exchange,提问作者Bruno Justino Praciano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:56:21