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()
复制代码
相关推荐
代码山河7 小时前
Python就业方向全解析:后端、爬虫、数据分析、AI你选哪个?
python·学习·架构·教程·面向对象·项目
在世修行7 小时前
智学文枢:题目流水线
python·多线程·状态机·pyside
梯度下降者7 小时前
零基础入门Python 爬虫
爬虫·python·数据分析·入门指南·webcrawler
“AI国潮设计-小江”9 小时前
【AIGC实战】Python+Stable Diffusion打造“英歌舞财神”IP,解锁“马到成功”等爆款情绪营销文案设计
开发语言·人工智能·python·prompt·aigc
benchmark_cc10 小时前
用 Python 拉 A 股全市场实时快照:Notebook 请求、结果校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
伞伞悦读10 小时前
【第70期】Adam二阶矩不是方差:偏差校正、动量与AdamW完整实验
python
外收内放10 小时前
Python基础语法练习题(73)
java·前端·python
锋行天下11 小时前
Langgraph HITL 中断运行,用户输入后输出打字效果
人工智能·python
时早玖沐11 小时前
给 AstrBot 写一个天气推送插件:12 次提交、6 个坑
python·开源·ai编程
触底反弹11 小时前
🚀 FastAPI 五大重难点深度剖析:从 500 报错到彻底搞懂 Depends、Pydantic 与 SQLAlchemy
python·fastapi