server.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from fastapi import FastAPI, Request, Response
  4. from starlette.middleware.cors import CORSMiddleware
  5. from admin.api.router import router as admin_router
  6. from app.api.router import router as app_router
  7. from auth import router as auth_router
  8. from common.endpoints import router as common_router
  9. from core.config import settings
  10. def create_app():
  11. app = FastAPI(title=settings.PROJECT_NAME,
  12. openapi_url=f"/{settings.API_V1_STR}/openapi.json")
  13. # cors
  14. register_cors(app)
  15. # router
  16. register_router(app)
  17. # exception
  18. register_exception(app)
  19. # interceptor
  20. register_interceptor(app)
  21. # middlewares
  22. # app.add_middleware(CasbinMiddleware, enforcer=enforcer)
  23. # app.add_middleware(AuthenticationMiddleware, backend=JwtAuth())
  24. return app
  25. def register_cors(app: FastAPI) -> None:
  26. if settings.DEBUG and settings.BACKEND_CORS_ORIGINS:
  27. app.add_middleware(
  28. CORSMiddleware,
  29. allow_origins=[
  30. str(origin) for origin in settings.BACKEND_CORS_ORIGINS
  31. ],
  32. allow_credentials=True,
  33. allow_methods=["*"],
  34. allow_headers=["*"],
  35. )
  36. def register_router(app: FastAPI) -> None:
  37. routers = [admin_router, auth_router, app_router, common_router]
  38. for router in routers:
  39. app.include_router(router, prefix="/" + settings.API_V1_STR)
  40. def register_exception(app: FastAPI) -> None:
  41. pass
  42. def register_interceptor(app: FastAPI) -> None:
  43. """
  44. 请求响应拦截器
  45. """
  46. @app.middleware("http")
  47. async def logger_request(request: Request, call_next) -> Response:
  48. print(
  49. f"Method:{request.method}, Url:{request.url}, IP:{request.client.host}"
  50. )
  51. return await call_next(request)