middleware.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from typing import Union, Optional
  2. from fastapi import FastAPI, Request, Body, Form, Query
  3. from fastapi.websockets import WebSocket, WebSocketDisconnect
  4. from fastapi.exceptions import RequestValidationError
  5. from fastapi.responses import JSONResponse
  6. from fastapi.staticfiles import StaticFiles
  7. from fastapi.middleware.cors import CORSMiddleware
  8. from starlette.exceptions import HTTPException
  9. from settings import *
  10. import random
  11. import os
  12. from pydantic import BaseModel, validator, conint, constr, Field
  13. # 关闭文档
  14. app = FastAPI()
  15. # app.mount("/model", StaticFiles(directory="model"), name="model")
  16. app.add_middleware(
  17. CORSMiddleware,
  18. # 允许跨域的源列表,例如 ["http://www.example.org"] 等等,["*"] 表示允许任何源
  19. allow_origins=["*"],
  20. # 跨域请求是否支持 cookie,默认是 False,如果为 True,allow_origins 必须为具体的源,不可以是 ["*"]
  21. allow_credentials=False,
  22. # 允许跨域请求的 HTTP 方法列表,默认是 ["GET"]
  23. allow_methods=["*"],
  24. # 允许跨域请求的 HTTP 请求头列表,默认是 [],可以使用 ["*"] 表示允许所有的请求头
  25. # 当然 Accept、Accept-Language、Content-Language 以及 Content-Type 总之被允许的
  26. allow_headers=["*"],
  27. # 可以被浏览器访问的响应头, 默认是 [],一般很少指定
  28. # expose_headers=["*"]
  29. # 设定浏览器缓存 CORS 响应的最长时间,单位是秒。默认为 600,一般也很少指定
  30. # max_age=1000
  31. )
  32. class UnicornException(Exception):
  33. def __init__(self, msg: str, code: int = -1):
  34. self.msg = msg
  35. self.code = code
  36. @app.exception_handler(UnicornException)
  37. async def error_throw(request: Request, exc: UnicornException):
  38. return JSONResponse(
  39. status_code=200,
  40. content={
  41. "code": exc.code,
  42. "msg": exc.msg,
  43. },
  44. )
  45. @app.exception_handler(HTTPException)
  46. async def global_exception_handler(request, exc):
  47. if exc.status_code == 500:
  48. err_msg = "Server Internal Error"
  49. else:
  50. err_msg = exc.detail
  51. return JSONResponse(
  52. {"code": exc.status_code, "err_msg": err_msg, "status": "Failed"}
  53. )