from fastapi import FastAPI, Request, Form from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from fastapi.responses import JSONResponse import uvicorn import os app = FastAPI(title="下载工具", version="1.0.0") # 挂载静态文件和模板 app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") @app.get("/") async def home(request: Request): """主页面""" return templates.TemplateResponse("index.html", {"request": request}) @app.post("/load_urls") async def load_urls(): """读取 targets.txt 文件中的URL""" try: file_path = "data/targets.txt" # 检查文件是否存在 if not os.path.exists('data'): os.mkdir('data') return JSONResponse({ "success": False, "message": f"文件 {file_path} 不存在", "urls": [] }) # 检查导入url配置是否存在 if not os.path.exists(file_path): return JSONResponse({ "success": False, "message": f"文件 {file_path} 不存在", "urls": [] }) # 读取文件内容 with open(file_path, 'r', encoding='utf-8') as f: urls = [line.strip() for line in f.readlines() if line.strip()] # 过滤掉空行和注释行(以#开头的行) urls = [url for url in urls if url and not url.startswith('#')] return JSONResponse({ "success": True, "message": f"成功读取 {len(urls)} 个URL", "urls": urls }) except Exception as e: return JSONResponse({ "success": False, "message": f"读取文件时出错: {str(e)}", "urls": [] }) @app.post("/clear") async def clear_output(): """清除输出""" return JSONResponse({ "success": True, "message": "输出已清除", "output": "" }) if __name__ == "__main__": uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)