main.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from fastapi import FastAPI, Request
  2. from fastapi.exceptions import RequestValidationError
  3. from fastapi.responses import JSONResponse
  4. from app.api.modbus import router as modbus_router
  5. from app.api.s7 import router as s7_router
  6. from app.response import response_payload
  7. def validation_error_message(exc: RequestValidationError) -> str:
  8. messages: list[str] = []
  9. for error in exc.errors():
  10. location = ".".join(str(item) for item in error.get("loc", []) if item != "body")
  11. message = error.get("msg", "validation error")
  12. messages.append(f"{location}: {message}" if location else message)
  13. return "; ".join(messages) or "validation error"
  14. def create_app() -> FastAPI:
  15. app = FastAPI(title="Data Collector Gateway")
  16. app.include_router(modbus_router, prefix="/api/dc-gateway")
  17. app.include_router(s7_router, prefix="/api/dc-gateway")
  18. @app.exception_handler(RequestValidationError)
  19. async def request_validation_exception_handler(
  20. request: Request,
  21. exc: RequestValidationError,
  22. ) -> JSONResponse:
  23. data: dict[str, list] = {}
  24. if request.url.path.endswith("/modbus/read"):
  25. data = {"communication": []}
  26. elif request.url.path.endswith(("/modbus/read_points", "/modbus/read-points")):
  27. data = {"points": []}
  28. elif request.url.path.endswith("/s7/read"):
  29. data = {"communication": []}
  30. elif request.url.path.endswith("/s7/read_points"):
  31. data = {"points": []}
  32. elif request.url.path.endswith("/s7/connect_scan"):
  33. data = {"available": []}
  34. return JSONResponse(
  35. status_code=200,
  36. content=response_payload(1, validation_error_message(exc), data),
  37. )
  38. return app
  39. app = create_app()
  40. def main() -> None:
  41. import uvicorn
  42. uvicorn.run(app, host="0.0.0.0", port=8000)