main.py 4.3 KB

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