Skip to content
有问题可以在公众号反馈 ✨
微信二维码

扫码留言

notion 集成配置

更新: 1970/1/1 字数: 0 字 时长: 0 分钟

1. 背景

  1. 目前网站文档的确难以管理,又懒得去做 wrdepress,想兼顾现在的页面

2. notion 配置

  1. 首先配置集成 alt textalt text

  2. 获取数据库的 id

  3. 代码获取数据库内容(但是实现后不知道干嘛,感觉又要自己重写一套前端一样)

    python
    import os
    import json
    import requests
    
    
     # 获取环境变量中的 NOTION_API_KEY,若没有,则使用默认值
    
     NOTION_API_KEY = os.environ.get("NOTION_API_KEY",
     "ntn_16317302003br") # 替换为你自己的 API 密钥
     DATABASE_ID = "27d3cc96678e7f10c" # 替换为你在 Notion 中的数据库 ID
    
     NOTION_API_URL = f"https://api.notion.com/v1/databases/{DATABASE_ID}/query"
    
     # Notion API 请求头
    
     HEADERS = {
     "Authorization": f"Bearer {NOTION_API_KEY}",
     "Notion-Version": "2022-06-28", # 使用最新的 Notion API 版本
     "Content-Type": "application/json",
     }
    
     # 安全获取标题字段
    
     def safe_get_title(page, prop_name="名称"): # 修改字段名称为 "名称"
     try:
     arr = page["properties"][prop_name]["title"]
     return arr[0]["text"]["content"] if arr else ""
     except Exception:
     return ""
    
     # 安全获取多选字段
    
     def safe_get_multi_select(page, prop_name="多选"): # 修改字段名称为 "多选"
     try:
     arr = page["properties"][prop_name]["multi_select"]
     return [item["name"] for item in arr] if arr else []
     except Exception:
     return []
    
     # 获取 Notion 数据库内容
    
     def fetch_notion_articles():
     has_more = True
     start_cursor = None
     while has_more:
     body = {}
     if start_cursor:
     body["start_cursor"] = start_cursor
    
             # 发出请求获取数据库内容
             print(f"Sending request to: {NOTION_API_URL}")
             resp = requests.post(NOTION_API_URL, headers=HEADERS, data=json.dumps(body))
    
             # 打印响应状态
             print(f"Response Status Code: {resp.status_code}")
    
             if resp.status_code != 200:
                 print(f"Error fetching articles: {resp.status_code}")
                 print(f"Response Text: {resp.text}")
                 return
    
             data = resp.json()
    
             # 打印返回的 JSON 数据
             print(f"Response JSON: {json.dumps(data, indent=2)}")
    
             results = data.get("results", [])
             if not results:
                 print("No results found.")
    
             # 遍历每个页面,打印 properties 字段内容
             for page in results:
                 print(f"Page ID: {page['id']}")
                 print(f"Properties: {json.dumps(page['properties'], indent=2)}")  # 打印属性字段
    
                 title = safe_get_title(page, "名称")  # 确保列名与数据库一致
                 multi_select = safe_get_multi_select(page, "多选")
                 print(f"Title: {title}\nMulti Select: {', '.join(multi_select)}\n")
    
             has_more = data.get("has_more", False)
             start_cursor = data.get("next_cursor")
             print(f"Has more: {has_more}")
             if start_cursor:
                 print(f"Next cursor: {start_cursor}")
    
     if **name** == "**main**":
     fetch_notion_articles()