1- import os , threading , datetime
2- from fastapi import Request
1+ import os , threading , datetime , sys , asyncio
2+ from fastapi .middleware .cors import CORSMiddleware
3+ from fastapi .exceptions import RequestValidationError
34from starlette .exceptions import HTTPException as StarletteHTTPException
4- from starlette .middleware .sessions import SessionMiddleware
55from tortoise .contrib .fastapi import register_tortoise
66
77from src .app import create_app
88from src .app .routes import router as main_router
99from src .app .exceptions import (
1010 custom_http_exception_handler ,
1111 universal_exception_handler ,
12+ custom_validation_exception_handler ,
1213)
1314
1415from src .Utils .Config import config # 导入配置模块
1516from src .Utils .HeartBeat import heartbeat_check_start
1617from src .Utils .MessageState import AppState
1718
19+ if sys .platform == "win32" :
20+ asyncio .set_event_loop_policy (asyncio .WindowsSelectorEventLoopPolicy ())
1821APP_START_TIME = datetime .datetime .now ()
1922AppState .set_start_time (APP_START_TIME )
2023app = create_app ()
2730app .include_router (main_router )
2831app .add_exception_handler (StarletteHTTPException , custom_http_exception_handler )
2932app .add_exception_handler (Exception , universal_exception_handler )
33+ app .add_exception_handler (RequestValidationError , custom_validation_exception_handler )
3034
3135uvicorn_config = {
3236 "app" : "main:app" ,
3842}
3943
4044
41- app .add_middleware (SessionMiddleware , secret_key = config .Advanced .session_secret )
42- @app .middleware ("http" )
43- async def session_middleware (request : Request , call_next ):
44- # 初始化会话
45- if not hasattr (request .state , "session" ):
46- request .state .session = {}
4745
48- response = await call_next (request )
49- return response
46+ app .add_middleware (
47+ CORSMiddleware ,
48+ allow_origins = ["*" ], # 前端开发服务器地址
49+ allow_credentials = True ,
50+ allow_methods = ["*" ],
51+ allow_headers = ["*" ],
52+ )
5053
5154if __name__ == "__main__" :
5255 if not os .path .exists ("data" ):
@@ -86,4 +89,10 @@ async def session_middleware(request: Request, call_next):
8689 logger .warning ("请注意:HTTP协议下,开放平台无法发包至本框架,造成消息不可达,请在生产环境中启用SSL" )
8790 logger .info ("正在启动守护线程..." )
8891 threading .Thread (target = heartbeat_check_start , daemon = True , name = "心跳检查线程" ).start ()
89- threading .Thread (target = uvicorn .run (** uvicorn_config ), daemon = False , name = "Uvicorn主线程" ).start () # 启动Uvicorn服务器
92+ uvicorn .run (
93+ loop = "asyncio" ,
94+ http = "httptools" if sys .platform != "win32" else "auto" ,
95+ timeout_keep_alive = 1 , # 空闲连接1秒关闭
96+ timeout_graceful_shutdown = 1 , # 关闭时等待1秒
97+ ** uvicorn_config
98+ )
0 commit comments