-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_files.py
More file actions
43 lines (36 loc) · 7.69 KB
/
setup_files.py
File metadata and controls
43 lines (36 loc) · 7.69 KB
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
import os
def setup_backend_files():
backend_path = os.path.join(os.getcwd(), 'backend')
static_path = os.path.join(backend_path, 'static')
html_file_path = os.path.join(static_path, 'test_api.html')
# 1. 创建 static 目录
print(f"正在创建目录: {static_path}")
os.makedirs(static_path, exist_ok=True)
print("目录创建或已存在!")
# 2. 写入 test_api.html 内容
html_content = """<!DOCTYPE html><html lang=\"zh-CN\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><title>嵌入式Linux智能教学平台 - API测试</title><style>body{font-family:\'Microsoft YaHei\', Arial, sans-serif;max-width:800px;margin:0 auto;padding:20px;background-color:#f5f5f5}.container{background:white;padding:30px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.1)}h1{color:#2c3e50;text-align:center;margin-bottom:30px}.section{margin-bottom:30px;padding:20px;border:1px solid #ddd;border-radius:5px;background-color:#f9f9f9}.section h2{color:#34495e;margin-top:0}.form-group{margin-bottom:15px}label{display:block;margin-bottom:5px;font-weight:bold;color:#555}input,select{width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;font-size:14px}button{background-color:#3498db;color:white;padding:12px 24px;border:none;border-radius:4px;cursor:pointer;font-size:16px;margin-right:10px}button:hover{background-color:#2980b9}.result{margin-top:15px;padding:15px;border-radius:4px;white-space:pre-wrap;font-family:monospace}.success{background-color:#d4edda;border:1px solid #c3e6cb;color:#155724}.error{background-color:#f8d7da;border:1px solid #f5c6cb;color:#721c24}.info{background-color:#d1ecf1;border:1px solid #bee5eb;color:#0c5460}</style></head><body><div class=\"container\"><h1>🚀 嵌入式Linux智能教学平台 - API测试</h1><div class=\"section\"><h2>📝 用户注册</h2><div class=\"form-group\"><label for=\"reg-username\">用户名:</label><input type=\"text\" id=\"reg-username\" placeholder=\"请输入用户名\"></div><div class=\"form-group\"><label for=\"reg-email\">邮箱:</label><input type=\"email\" id=\"reg-email\" placeholder=\"请输入邮箱\"></div><div class=\"form-group\"><label for=\"reg-password\">密码:</label><input type=\"password\" id=\"reg-password\" placeholder=\"请输入密码\"></div><div class=\"form-group\"><label for=\"reg-role\">角色:</label><select id=\"reg-role\"><option value=\"student\">学生</option><option value=\"teacher\">教师</option><option value=\"admin\">管理员</option></select></div><button onclick=\"register()\">注册用户</button><div id=\"register-result\" class=\"result\" style=\"display: none;\"></div></div><div class=\"section\"><h2>🔐 用户登录</h2><div class=\"form-group\"><label for=\"login-username\">用户名:</label><input type=\"text\" id=\"login-username\" placeholder=\"请输入用户名\"></div><div class=\"form-group\"><label for=\"login-password\">密码:</label><input type=\"password\" id=\"login-password\" placeholder=\"请输入密码\"></div><button onclick=\"login()\">登录</button><div id=\"login-result\" class=\"result\" style=\"display: none;\"></div></div><div class=\"section\"><h2>👤 获取用户信息</h2><button onclick=\"getUserInfo()\">获取当前用户信息</button><div id=\"userinfo-result\" class=\"result\" style=\"display: none;\"></div></div><div class=\"section\"><h2>💚 健康检查</h2><button onclick=\"healthCheck()\">检查服务状态</button><div id=\"health-result\" class=\"result\" style=\"display: none;\"></div></div></div><script>let currentToken='';function showResult(elementId,message,type='info'){const element=document.getElementById(elementId);element.textContent=message;element.className=`result ${type}`;element.style.display='block'}async function register(){const username=document.getElementById('reg-username').value;const email=document.getElementById('reg-email').value;const password=document.getElementById('reg-password').value;const role=document.getElementById('reg-role').value;if(!username||!email||!password){showResult('register-result','请填写所有必填字段!','error');return}try{const response=await fetch('http://localhost:8000/register',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:username,email:email,password:password,role:role})});const data=await response.json();if(response.ok){showResult('register-result',`✅ 注册成功!\\n用户ID: ${data.id}\\n用户名: ${data.username}\\n邮箱: ${data.email}\\n角色: ${data.role}`,'success')}else{showResult('register-result',`❌ 注册失败:${data.detail}`,'error')}}catch(error){showResult('register-result',`❌ 网络错误:${error.message}`,'error')}}async function login(){const username=document.getElementById('login-username').value;const password=document.getElementById('login-password').value;if(!username||!password){showResult('login-result','请填写用户名和密码!','error');return}try{const formData=new FormData();formData.append('username',username);formData.append('password',password);const response=await fetch('http://localhost:8000/token',{method:'POST',body:formData});const data=await response.json();if(response.ok){currentToken=data.access_token;showResult('login-result',`✅ 登录成功!\\nToken: ${data.access_token}\\nToken类型: ${data.token_type}`,'success')}else{showResult('login-result',`❌ 登录失败:${data.detail}`,'error')}}catch(error){showResult('login-result',`❌ 网络错误:${error.message}`,'error')}}async function getUserInfo(){if(!currentToken){showResult('userinfo-result','❌ 请先登录获取Token!','error');return}try{const response=await fetch('http://localhost:8000/me',{method:'GET',headers:{'Authorization':`Bearer ${currentToken}`}});const data=await response.json();if(response.ok){showResult('userinfo-result',`✅ 用户信息:\\n用户ID: ${data.id}\\n用户名: ${data.username}\\n邮箱: ${data.email}\\n角色: ${data.role}\\n状态: ${data.is_active?'激活':'未激活'}\\n创建时间: ${data.created_at}`,'success')}else{showResult('userinfo-result',`❌ 获取用户信息失败:${data.detail}`,'error')}}catch(error){showResult('userinfo-result',`❌ 网络错误:${error.message}`,'error')}}async function healthCheck(){try{const response=await fetch('http://localhost:8000/health');const data=await response.json();if(response.ok){showResult('health-result',`✅ 服务状态:${data.status}`,'success')}else{showResult('health-result',`❌ 服务异常:${data.detail}`,'error')}}catch(error){showResult('health-result',`❌ 无法连接到服务:${error.message}`,'error')}}</script></body></html>'''
print(f"正在写入文件: {html_file_path}")
with open(html_file_path, 'w', encoding='utf-8') as f:
f.write(html_content)
print("文件写入完成!")
if __name__ == "__main__":
# 确保当前工作目录是项目根目录 D:\Software Cup-14
# 如果不是,则手动切换
current_dir = os.getcwd()
expected_dir = 'D:\\Software Cup-14'
if not current_dir.endswith(expected_dir):
# 尝试向上切换目录直到找到项目根目录
path_parts = current_dir.split(os.sep)
project_root_index = -1
for i, part in enumerate(path_parts):
if part.lower() == 'software cup-14':
project_root_index = i
break
if project_root_index != -1:
target_dir = os.path.join(*path_parts[:project_root_index+1])
os.chdir(target_dir)
print(f"已切换到项目根目录: {os.getcwd()}")
else:
print("警告: 无法自动切换到项目根目录。请确保在 D:\\Software Cup-14 目录下运行此脚本。")
exit()
setup_backend_files()