|
|
@@ -0,0 +1,64 @@
|
|
|
+from typing import Union, Optional
|
|
|
+from fastapi import FastAPI, Request, Body, Form, Query
|
|
|
+from fastapi.websockets import WebSocket
|
|
|
+from fastapi.exceptions import RequestValidationError
|
|
|
+from fastapi.responses import JSONResponse
|
|
|
+from fastapi.staticfiles import StaticFiles
|
|
|
+from fastapi.middleware.cors import CORSMiddleware
|
|
|
+from starlette.exceptions import HTTPException
|
|
|
+from settings import *
|
|
|
+import random
|
|
|
+import os
|
|
|
+from pydantic import BaseModel, validator, conint, constr, Field
|
|
|
+
|
|
|
+# 关闭文档
|
|
|
+app = FastAPI()
|
|
|
+# app.mount("/model", StaticFiles(directory="model"), name="model")
|
|
|
+app.add_middleware(
|
|
|
+ CORSMiddleware,
|
|
|
+ # 允许跨域的源列表,例如 ["http://www.example.org"] 等等,["*"] 表示允许任何源
|
|
|
+ allow_origins=["*"],
|
|
|
+ # 跨域请求是否支持 cookie,默认是 False,如果为 True,allow_origins 必须为具体的源,不可以是 ["*"]
|
|
|
+ allow_credentials=False,
|
|
|
+ # 允许跨域请求的 HTTP 方法列表,默认是 ["GET"]
|
|
|
+ allow_methods=["*"],
|
|
|
+ # 允许跨域请求的 HTTP 请求头列表,默认是 [],可以使用 ["*"] 表示允许所有的请求头
|
|
|
+ # 当然 Accept、Accept-Language、Content-Language 以及 Content-Type 总之被允许的
|
|
|
+ allow_headers=["*"],
|
|
|
+ # 可以被浏览器访问的响应头, 默认是 [],一般很少指定
|
|
|
+ # expose_headers=["*"]
|
|
|
+ # 设定浏览器缓存 CORS 响应的最长时间,单位是秒。默认为 600,一般也很少指定
|
|
|
+ # max_age=1000
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+class UnicornException(Exception):
|
|
|
+ def __init__(self, msg: str, code: int = -1):
|
|
|
+ self.msg = msg
|
|
|
+ self.code = code
|
|
|
+
|
|
|
+@app.exception_handler(UnicornException)
|
|
|
+async def error_throw(request: Request, exc: UnicornException):
|
|
|
+
|
|
|
+ return JSONResponse(
|
|
|
+ status_code=200,
|
|
|
+ content={
|
|
|
+ "code": exc.code,
|
|
|
+ "msg": exc.msg,
|
|
|
+ },
|
|
|
+ )
|
|
|
+
|
|
|
+
|
|
|
+@app.exception_handler(HTTPException)
|
|
|
+async def global_exception_handler(request, exc):
|
|
|
+ if exc.status_code == 500:
|
|
|
+ err_msg = "Server Internal Error"
|
|
|
+ else:
|
|
|
+ err_msg = exc.detail
|
|
|
+ return JSONResponse(
|
|
|
+ {"code": exc.status_code, "err_msg": err_msg, "status": "Failed"}
|
|
|
+ )
|
|
|
+@app.on_event("shutdown")
|
|
|
+async def shutdown_event():
|
|
|
+ # 清理操作
|
|
|
+ print("服务关闭完成,done!")
|