From a8b46cf810398604f94af0578e64230b58e64031 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=82=A6?= Date: Thu, 11 Jul 2024 18:11:03 +0800 Subject: [PATCH] Update server.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 接口服务允许跨域请求,接入其他服务,比如ollama或者其他大模型服务 --- runtime/python/fastapi/server.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/runtime/python/fastapi/server.py b/runtime/python/fastapi/server.py index b0bf62c..b670665 100644 --- a/runtime/python/fastapi/server.py +++ b/runtime/python/fastapi/server.py @@ -10,6 +10,7 @@ import sys import io,time from fastapi import FastAPI, Response, File, UploadFile, Form from fastapi.responses import HTMLResponse +from fastapi.middleware.cors import CORSMiddleware #引入 CORS中间件模块 from contextlib import asynccontextmanager ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append('{}/../../..'.format(ROOT_DIR)) @@ -39,6 +40,15 @@ async def lifespan(app: FastAPI): app = FastAPI(lifespan=lifespan) +#设置允许访问的域名 +origins = ["*"] #"*",即为所有,也可以改为允许的特定ip。 +app.add_middleware( + CORSMiddleware, + allow_origins=origins, #设置允许的origins来源 + allow_credentials=True, + allow_methods=["*"], # 设置允许跨域的http方法,比如 get、post、put等。 + allow_headers=["*"]) #允许跨域的headers,可以用来鉴别来源等作用。 + def buildResponse(output): buffer = io.BytesIO() torchaudio.save(buffer, output, 22050, format="wav")