1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| import requests import os,time
BASE_URL = "http://172.16.11.53/console/api" EMAIL = "[email protected]" PASSWORD = "****" IMPORT_DIR = f"./dify_backups/{time.strftime('%Y%m%d')}"
class DifyImporter: def __init__(self): self.session = requests.Session()
def login(self): url = f"{BASE_URL}/login" res = self.session.post(url, json={"email": EMAIL, "password": PASSWORD}) if res.status_code == 200: data = res.json().get("data", {}) self.session.headers.update({ "Authorization": f"Bearer {data.get('access_token')}", "X-Csrf-Token": self.session.cookies.get("csrf_token"), "Content-Type": "application/json" }) print("✅ 登录成功") return True print(f"❌ 登录失败: {res.text}") return False
def do_import(self, file_path): url = f"{BASE_URL}/apps/imports" file_name = os.path.basename(file_path) try: with open(file_path, 'r', encoding='utf-8-sig') as f: dsl_content = f.read()
payload = { "mode": "yaml-content", "yaml_content": dsl_content } response = self.session.post(url, json=payload) res_json = response.json() if response.status_code in [200, 201] and res_json.get("status") != "failed": print(f"✨ 成功导入: {file_name}") else: print(f"❌ 导入失败: {file_name}") print(f" 状态码: {response.status_code}") print(f" 详细错误: {res_json.get('error', response.text)}") except Exception as e: print(f"🚨 脚本执行异常: {e}")
def run(self): if self.login(): files = [f for f in os.listdir(IMPORT_DIR) if f.endswith(('.yml', '.yaml'))] if not files: print("📭 备份目录中没有发现 .yml 文件") return for f in files: print(f"🚀 正在尝试导入: {f}") self.do_import(os.path.join(IMPORT_DIR, f))
if __name__ == "__main__": DifyImporter().run()
|