将数据库中其他表的数据同步到一个 新的飞书多维表格(Base 和 Table 链接如下):
Base: https://z1x96jlwely.feishu.cn/base/G36wbfZa6augZVsdvNycxjwxnJf
Table ID: tbl2tWORpoxr0q8P
View ID: vew5n09HVQ(可忽略,不影响写入)
你要在 settings.py 或 .env 对应配置文件中,加入新的表配置:
FEISHU_SETTING = {
...
"new_table_sync": {
"app_token": "your_base_app_token", # 飞书 Base 的 token(可从开发后台获取)
"table_id": "tbl2tWORpoxr0q8P", # 表格 ID,对应 URL 中的参数
}
}
例如你可以新建一个函数 sync_new_table_feishu():
def sync_new_table_feishu():
setting = settings.FEISHU_SETTING["new_table_sync"]
app_token = setting["app_token"]
table_id = setting["table_id"]
# 删除表中旧数据(如不需要清空可以删除此行)
bitable_service.delete_all(app_token, table_id)
field_map = {
"飞书列1": "数据库字段1",
"飞书列2": "数据库字段2",
...
}
base_sql = """
SELECT id, 字段1, 字段2, ...
FROM your_table_name
...
"""
# 如果不依赖外部表数据(如仓库、品类等),可以传空字典
_insert_new_table_to_feishu(app_token, table_id, field_map, base_sql, {}, {})
这方法可以改名复用逻辑:
def _insert_new_table_to_feishu(app_token, table_id, field_map, base_sql, warehouses, product_categories):
lastId = None
while True:
sql = f"""{base_sql}
{" WHERE id > " + db_util.xstr2(lastId) if lastId is not None else ''}
ORDER BY id ASC
LIMIT 1000"""
data = db_util.query(sql=sql)
if not data:
break
# 如需清洗或加工数据,可在此调用你自定义的处理函数
_process_new_table_data(data)
bitable_service.batch_insert_with_record_ids(app_token, table_id, data, field_map)
lastId = data[-1].get("id")
print(f"Inserted batch, lastId: {lastId}")
如果你的数据不需要处理时间、金额、匹配外部表,可以简单 pass,也可以做一些字段清洗:
def _process_new_table_data(data):
for item in data:
# 比如:将时间字段转为毫秒时间戳
if item.get("created_at"):
item["created_at"] = int(item["created_at"].timestamp() * 1000)
# 格式化数字
item["amount"] = format_as_num(item.get("amount") or 0)
原代码位置 | 需要你修改的内容 |
---|---|
settings.FEISHU_SETTING |
添加新飞书表的配置(app_token 和 table_id) |
sync_ship_batch_feishu |
新建一个类似函数:如 sync_new_table_feishu() |
base_sql |
改为查询你目标数据表的 SQL |
field_map |
映射新表字段(飞书列名 → SQL字段名) |
_process_ship_batch_data() |
改名为 _process_new_table_data() 并按需修改处理逻辑 |
warehouses, product_categories |
如无需使用可传入空字典 {} |
假设你要把订单表 xss_order 的数据同步到飞书表,有如下字段映射:
飞书字段 | 数据库字段 |
---|---|
订单号 | order_no |
客户名称 | customer_name |
下单时间 | created_at |
金额 | total_amount |
那么你只需定义:
field_map = {
"订单号": "order_no",
"客户名称": "customer_name",
"下单时间": "created_at",
"金额": "total_amount",
}
base_sql = "SELECT id, order_no, customer_name, created_at, total_amount FROM xss_order"