main.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import importlib
  2. import json
  3. import os
  4. import time
  5. import fastapi
  6. from fastapi import FastAPI
  7. from fastapi import HTTPException, Request
  8. from fastapi.exceptions import RequestValidationError
  9. from fastapi.middleware.cors import CORSMiddleware
  10. from fastapi.responses import PlainTextResponse
  11. from pydantic import BaseModel # 参数校验
  12. from starlette.exceptions import HTTPException as StarletteHTTPException
  13. from starlette.middleware.sessions import SessionMiddleware
  14. from starlette.responses import JSONResponse, RedirectResponse
  15. from starlette.staticfiles import StaticFiles
  16. from config import logger, CfgBaseInit
  17. app = FastAPI(title="project name ", description="通用系统 ", version="v 0.0.0")
  18. # app.routes.pop(1) # drop default docs_url router
  19. # 添加 session 中间键,使项目中可以使用session
  20. app.add_middleware(SessionMiddleware, secret_key='123456hhh')
  21. app.add_middleware(
  22. CORSMiddleware,
  23. allow_origins=["*", ],
  24. allow_credentials=True,
  25. allow_methods=["*"],
  26. allow_headers=["*"],
  27. )
  28. static_obj = StaticFiles(directory="static", html=True)
  29. app.mount("/static", static_obj, "static")
  30. @app.exception_handler(StarletteHTTPException)
  31. async def http_exception_handler(request, exc):
  32. """接口服务异常捕获; text/plain"""
  33. return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
  34. @app.exception_handler(RequestValidationError)
  35. async def validation_exception_handler(request, exc):
  36. """请求校验异常捕获; application/json """
  37. json_response = JSONResponse({'message': '【 {} 】接口触发了 RequestValidationError 错误.'
  38. .format(request.scope.get("endpoint").__name__, exc.errors()), 'status_code': 999,
  39. "error_message": exc.errors(), "queryParasm": exc.body})
  40. logger.error(json.loads(json_response.body))
  41. return json_response
  42. @app.exception_handler(Exception)
  43. async def validation_exception_handler(request, exc):
  44. """请求校验异常捕获; application/json """
  45. return JSONResponse({'message': "服务器内部错误", 'status_code': 500})
  46. @app.middleware("http")
  47. async def add_process_time_header(request: Request, call_next):
  48. """接口响应中间键; 当前只支持 http 请求"""
  49. logger.info(f'【 {request.scope.get("path")} 】API query start...')
  50. start_time = time.time()
  51. response = await call_next(request)
  52. process_time = time.time() - start_time
  53. response.headers["API-Process-Time"] = f"{process_time} seconds"
  54. logger.info(f'【 {request.scope.get("path")} 】API, Time:【 {process_time} seconds 】...')
  55. return response
  56. # 动态注册路由
  57. for file in os.listdir(os.path.join(CfgBaseInit.project_path, "controller")):
  58. if not file.endswith("py") or '__init__.py' in file:
  59. continue
  60. file = file.split('.')[0]
  61. router_module = importlib.import_module(f"controller.{file}", package=None)
  62. if hasattr(router_module, "router"):
  63. # 注册路由
  64. app.include_router(
  65. router_module.router,
  66. # dependencies=[Depends(get_token_header)],
  67. responses={404: {"description": "Not found"}},
  68. )
  69. @app.get("/")
  70. def index():
  71. return RedirectResponse(url="/static/index.html")
  72. # http://localhost:8000/query?uid=1
  73. @app.get("/query")
  74. def query(uid):
  75. msg = f'uid为{uid}'
  76. return {'success': True, 'msg': msg}
  77. # http://localhost:8000/query/1 参数类型有校验
  78. @app.get("/query/{uid}")
  79. def query(uid: int):
  80. msg = f'uid为{uid}'
  81. return {'success': True, 'msg': msg}
  82. class People(BaseModel):
  83. name: str
  84. age: int
  85. address: str
  86. salary: float
  87. # json body请求
  88. @app.post("/insert")
  89. def insert(people: People):
  90. msg = f"名字:{people.name},年龄{people.age}"
  91. return msg