main.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import uvicorn
  2. import logging
  3. from fastapi import FastAPI, BackgroundTasks, Request
  4. from contextlib import asynccontextmanager
  5. from pydantic import BaseModel
  6. from typing import List
  7. import threading
  8. import time
  9. from conf.settings import logger,HOST,PORT
  10. from task import Thread_que,run_task,detect_list
  11. @asynccontextmanager
  12. async def lifespan(app: FastAPI):
  13. # 在应用启动前运行的函数
  14. thread = threading.Thread(target=run_task)
  15. thread.start()
  16. yield
  17. # 在应用关闭后运行的函数
  18. Thread_que.put_nowait("stop")
  19. thread.join()
  20. logger.info("Shutting down...")
  21. logger.info("FastAPI docs: ")
  22. app = FastAPI(lifespan=lifespan)
  23. class Item(BaseModel):
  24. str: str
  25. @app.get("/")
  26. async def list_detect_list():
  27. return detect_list.list
  28. @app.post("/")
  29. async def add_live(request: Request):
  30. json_body = await request.json()
  31. Thread_que.put_nowait({"add":json_body})
  32. # 你的代码
  33. return {"status": "ok"}
  34. def main():
  35. uvicorn.run(app, host=HOST, port=PORT, log_level="info")
  36. if __name__ == "__main__":
  37. main()