main.py 2.6 KB

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