python_更新飞书多维表格的单项关联字段

python_更新飞书多维表格的单项关联字段

python 复制代码
# 使用此指令前,请确保安装必要的Python库,例如使用以下命令安装:
# pip install requests

import requests
import json

from typing import *
try:
    from xbot.app.logging import trace as print
except:
    from xbot import print


def update_bitable_link_field_fixed(app_id, app_secret, app_token, table_id, record_id, field_name, linked_record_id):
    """
    title: 更新多维表格单项关联字段
    description: 自动获取 Token 并通过 PUT 方法更新多维表格 %app_token% 中指定记录 %record_id% 的关联字段 %field_name%。
    inputs:
        - app_id (str): 飞书自建应用的 App ID,eg: "cli_a5db1166713a900c"
        - app_secret (str): 飞书自建应用的 App Secret,eg: "Imdfwys4jb2VanubbZpoqd1elIhnItKy"
        - app_token (str): 多维表格的唯一标识,eg: "GZlfwzHIDijkLNklIGNcxNo3nbd"
        - table_id (str): 数据表的唯一标识,eg: "tblAO3koPJNcP9z0"
        - record_id (str): 待更新的记录 ID,eg: "rec27qGrNWq5pB"
        - field_name (str): 关联字段的名称(注意:必须是关联类型,不能是查阅类型),eg: "客户名称"
        - linked_record_id (str): 关联表中的目标记录 ID,eg: "recbcdefg123"
    outputs:
        - result (dict): API 返回的响应结果,eg: {"code": 0, "msg": "success", "data": {...}}
    """

    def _get_tenant_access_token(aid, asecret):
        """获取飞书租户访问凭证"""
        url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
        payload = {"app_id": aid.strip(), "app_secret": asecret.strip()}
        try:
            response = requests.post(url, json=payload)
            response.raise_for_status()
            data = response.json()
            if data.get("code") != 0:
                raise Exception(f"获取 Token 失败: {data.get('msg')}")
            return data.get("tenant_access_token")
        except Exception as e:
            raise Exception(f"身份验证失败,请检查 AppID 和 Secret: {str(e)}")

    def _update_record_put(token, app_tk, tab_id, rec_id, f_name, l_rec_id):
        """使用 PUT 方法更新记录"""
        # 去除参数两端的空格,防止 URL 拼接错误导致 404
        app_tk, tab_id, rec_id = app_tk.strip(), tab_id.strip(), rec_id.strip()
        
        url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{app_tk}/tables/{tab_id}/records/{rec_id}"
        
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json; charset=utf-8"
        }
        
        # 关联字段必须是字符串数组格式
        # 如果 linked_record_id 为空,则传空数组 [] 以清空关联
        val_list = [l_rec_id.strip()] if l_rec_id and str(l_rec_id).strip() else []
        
        payload = {
            "fields": {
                f_name: val_list
            }
        }
        
        try:
            # 官方文档指定使用 PUT 方法
            response = requests.put(url, headers=headers, json=payload)
            
            if response.status_code == 404:
                raise Exception(f"飞书返回 404:请检查多维表格ID、数据表ID或记录ID是否正确。当前请求URL: {url}")
            
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            err_msg = response.text if 'response' in locals() else str(e)
            raise Exception(f"请求飞书 API 失败: {err_msg}")

    # 1. 获取最新的 Token
    token = _get_tenant_access_token(app_id, app_secret)

    # 2. 执行更新操作
    result = _update_record_put(token, app_token, table_id, record_id, field_name, linked_record_id)
    
    if result.get("code") != 0:
        # 如果 code 为 1254405, 说明字段是只读的(如查阅字段)
        raise Exception(f"更新失败,飞书返回错误: {result.get('msg')} (错误码: {result.get('code')})")

    return result
相关推荐
染指11104 小时前
8.向量数据库-RAG基础2
大数据·数据库·人工智能·rag
2601_953660374 小时前
File类
linux·开发语言·python
随身数智备忘录4 小时前
从点检到全生命周期:设备管理体系能解决哪些场景痛点?一套设备管理体系的实战应用
java·网络·数据库
GIOTTO情4 小时前
Infoseek 媒介投放 API 实战:基于 Python 的全流程自动化方案摘要
开发语言·python·自动化
广州灵眸科技有限公司4 小时前
瑞芯微(EASY EAI)RV1126B 千兆以太网电路
服务器·前端·人工智能·python·深度学习
不太厉害的程序员4 小时前
Oracle使用工具PL/SQL Developer中的数据泵备份还原数据库
数据库·sql·oracle
三十六煩惱風4 小时前
2026-05/04~10技术问题处理
java·数据库·sql
丷丩4 小时前
Postgresql基础实践教程
数据库·postgresql
speop4 小时前
【thorough-pytorch】评价指标
人工智能·pytorch·python