main.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from fastapi import FastAPI, Request #, Response,HTTPException
  4. from fastapi.responses import JSONResponse, RedirectResponse
  5. from fastapi.exceptions import RequestValidationError
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from starlette.middleware.sessions import SessionMiddleware
  8. from starlette.staticfiles import StaticFiles
  9. from routers import home, api ,prod_api
  10. from exceptions import *
  11. from pymysql.err import OperationalError
  12. import os
  13. import platform
  14. app = FastAPI()
  15. # app.include_router(home.router)
  16. app.include_router(api.router, prefix="/api")
  17. app.include_router(prod_api.router, prefix="/prod_api")
  18. app.add_middleware(SessionMiddleware, secret_key='MM-ZHCS-YJ-API', max_age=36000 * 24)
  19. app.add_middleware(CORSMiddleware,allow_origins=['*'],allow_credentials=False,allow_methods=['*'],allow_headers=['*'])
  20. app.mount('/static', StaticFiles(directory='static'), name='static')
  21. # @app.exception_handler(RequestValidationError)
  22. # async def validation_exception_handler(request, exc):
  23. # return JSONResponse(status_code=200, content={ "errcode": 100060, "errmsg": "参数错误" }, )
  24. @app.exception_handler(TokenException)
  25. async def exception_handler(request: Request, exc: TokenException):
  26. return JSONResponse(
  27. status_code=200,
  28. content={"errcode": "4001", "errmsg":"验证不通过"}
  29. )
  30. @app.exception_handler(OperationalError)
  31. async def exception_handler(request: Request, exc: OperationalError):
  32. return JSONResponse(
  33. status_code=412,
  34. content={"code": "412", "msg":f"接口对应sql异常,请检查{exc}"}
  35. )
  36. # @app.exception_handler(AttributeError)
  37. # async def exception_handler(request: Request, exc: TokenException):
  38. # return JSONResponse(
  39. # status_code=200,
  40. # content={"errcode": "500", "errmsg":"Internal Server Error"}
  41. # )
  42. @app.exception_handler(AuthException)
  43. async def exception_handler(request: Request, exc: TokenException):
  44. return RedirectResponse("/")
  45. @app.exception_handler(AlertException)
  46. async def exception_handler(request: Request, exc: AlertException):
  47. return JSONResponse(
  48. status_code=200,
  49. content={"ret": 1, "msg": exc.msg}
  50. )
  51. if __name__ == '__main__':
  52. import uvicorn
  53. sys = platform.system()
  54. if sys == "Windows":
  55. os.system("title 茂名应急数据中台 DEV")
  56. # print(1234567890)
  57. uvicorn.run(app='main:app', host='0.0.0.0',port=9988, reload=True, debug=True)
  58. # uvicorn.run(app='main:app', host='0.0.0.0', port=9988)