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

Airflow出现File not found Error:JSON凭证文件无法被DAG识别如何解决?

解决Airflow DAG无法找到Google凭证JSON文件的问题

问题根源

Python的文件操作函数(包括ServiceAccountCredentials.from_json_keyfile_name底层调用的open())不会自动解析路径中的~(代表当前用户主目录),直接使用~/airflow/credential/client_secret.json会被当作字面路径,导致系统找不到对应文件。

具体解决方案

1. 使用绝对路径

直接替换为完整的绝对路径(根据你的报错信息,主目录为/Users/yifanhuang):

def upload():
    scope = ['https://spreadsheets.google.com/feeds']
    dicter = '/Users/yifanhuang/airflow/credential/client_secret.json'
    creds = ServiceAccountCredentials.from_json_keyfile_name(dicter, scope)
    client = gspread.authorize(creds)
    # 后续上传逻辑...

2. 用Python解析波浪号路径

通过os.path.expanduser()函数自动解析~为实际主目录路径:

import os

def upload():
    scope = ['https://spreadsheets.google.com/feeds']
    dicter = os.path.expanduser('~/airflow/credential/client_secret.json')
    creds = ServiceAccountCredentials.from_json_keyfile_name(dicter, scope)
    client = gspread.authorize(creds)
    # 后续上传逻辑...

3. 利用Airflow连接(推荐最佳实践)

避免硬编码路径,将凭证内容存入Airflow连接:

  • 打开Airflow UI,进入Admin -> Connections
  • 创建新连接,Conn Type选择Google Cloud Platform
  • 在Keyfile JSON字段粘贴client_secret.json的完整内容
  • 在代码中通过连接获取凭证:
from airflow.hooks.base_hook import BaseHook

def upload():
    scope = ['https://spreadsheets.google.com/feeds']
    # 替换为你创建的连接ID
    conn = BaseHook.get_connection('gcp_sheets_connection')
    creds = ServiceAccountCredentials.from_json_keyfile_dict(conn.extra_dejson['keyfile_json'], scope)
    client = gspread.authorize(creds)
    # 后续上传逻辑...

4. 验证文件权限与位置

  • 在终端执行ls ~/airflow/credential/client_secret.json,确认文件确实存在
  • 执行chmod 644 ~/airflow/credential/client_secret.json,确保Airflow运行用户有读取该文件的权限

内容的提问来源于stack exchange,提问作者TryingToLearnSomething

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:48:24