python 更新Obsidian

js 复制代码
import requests
import urllib.parse
import urllib3
import os
from dotenv import load_dotenv

# 忽略 HTTPS 警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
load_dotenv("../.env")
LOCAL_REST_API_KEY = os.getenv("LOCAL_REST_KEY")
BASE_URL = "https://127.0.0.1:27124"

def update_obsidian_locator_via_put(logical_id, new_selector):
    # 路径和 URL 编码保持不变
    file_path = f"LogicAnchors/{logical_id}.md"
    encoded_path = urllib.parse.quote(file_path, safe='')
    url = f"{BASE_URL}/vault/{encoded_path}"

    # PUT 模式通常只需要 Target-Type
    headers = {
        "Authorization": f"Bearer {LOCAL_REST_API_KEY}",
        "Content-Type": "application/json",
        "Target-Type": "frontmatter",
        "Target": "frontmatter"
    }

    # 注意:PUT 会根据这些 Key 自动匹配并更新
    payload = {
        "locator": new_selector,
        "status": "✅ Stable",
        "last_updated": "2026-04-16"
    }

    try:
        # 改用 PUT 方法
        response = requests.put(url, json=payload, headers=headers, verify=False)

        if response.status_code in [200, 204]:
            print(f"✅ 成功!通过 PUT 更新了 [[{logical_id}]]")
        else:
            print(f"❌ 还是失败 (PUT): {response.status_code}, {response.text}")
    except Exception as e:
        print(f"异常: {e}")


# 测试执行
update_obsidian_locator_via_put("LOGIN_INPUT_EMAIL", 'input[aria-label="New Email"]')

若是执行有问题的话,首先运行排查脚本:

python 复制代码
import requests
from dotenv import load_dotenv
import json
import os
load_dotenv("../.env")

# 配置你的 Obsidian 接口信息
LOCAL_REST_API_KEY = os.getenv("LOCAL_REST_KEY")
BASE_URL = "https://127.0.0.1:27124"
HEADERS = {
    "Authorization": f"Bearer {LOCAL_REST_API_KEY}",
    "Content-Type": "application/json"
}

def debug_list_files():
    # 尝试列出 Logic_Anchors01 文件夹下的所有文件
    debug_url = f"{BASE_URL}/vault/LogicAnchors/"
    response = requests.get(debug_url, headers=HEADERS, verify=False)

    if response.status_code == 200:
        files = response.json()
        print("📂 文件夹下的文件列表:")
        for f in files['files']:
            print(f" - {f}")
    else:
        print(f"❌ 无法读取文件夹,错误码: {response.status_code}")


# debug_list_files()
def get_vault_root_structure():
    # 重点:直接请求 /vault/,不要加任何文件夹名
    url = f"{BASE_URL}/vault/"

    # 禁用证书警告(本地测试)
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    response = requests.get(url, headers=HEADERS, verify=False)

    if response.status_code == 200:
        data = response.json()
        print("📁 当前库根目录下的内容:")
        # API 返回通常是一个包含 'files' 键的列表
        for item in data.get('files', []):
            print(f" - {item}")
    else:
        print(f"❌ 根目录访问失败: {response.status_code}, {response.text}")


# get_vault_root_structure()
复制代码
相关推荐
兵慌码乱44 分钟前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei4 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi0010 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn11 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏