main.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from fastapi import FastAPI, Request, Form
  2. from fastapi.staticfiles import StaticFiles
  3. from fastapi.templating import Jinja2Templates
  4. from fastapi.responses import JSONResponse
  5. import uvicorn
  6. import os
  7. app = FastAPI(title="下载工具", version="1.0.0")
  8. # 挂载静态文件和模板
  9. app.mount("/static", StaticFiles(directory="static"), name="static")
  10. templates = Jinja2Templates(directory="templates")
  11. @app.get("/")
  12. async def home(request: Request):
  13. """主页面"""
  14. return templates.TemplateResponse("index.html", {"request": request})
  15. @app.post("/load_urls")
  16. async def load_urls():
  17. """读取 targets.txt 文件中的URL"""
  18. try:
  19. file_path = "data/targets.txt"
  20. # 检查文件是否存在
  21. if not os.path.exists('data'):
  22. os.mkdir('data')
  23. return JSONResponse({
  24. "success": False,
  25. "message": f"文件 {file_path} 不存在",
  26. "urls": []
  27. })
  28. # 检查导入url配置是否存在
  29. if not os.path.exists(file_path):
  30. return JSONResponse({
  31. "success": False,
  32. "message": f"文件 {file_path} 不存在",
  33. "urls": []
  34. })
  35. # 读取文件内容
  36. with open(file_path, 'r', encoding='utf-8') as f:
  37. urls = [line.strip() for line in f.readlines() if line.strip()]
  38. # 过滤掉空行和注释行(以#开头的行)
  39. urls = [url for url in urls if url and not url.startswith('#')]
  40. return JSONResponse({
  41. "success": True,
  42. "message": f"成功读取 {len(urls)} 个URL",
  43. "urls": urls
  44. })
  45. except Exception as e:
  46. return JSONResponse({
  47. "success": False,
  48. "message": f"读取文件时出错: {str(e)}",
  49. "urls": []
  50. })
  51. @app.post("/clear")
  52. async def clear_output():
  53. """清除输出"""
  54. return JSONResponse({
  55. "success": True,
  56. "message": "输出已清除",
  57. "output": ""
  58. })
  59. if __name__ == "__main__":
  60. uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)