-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
83 lines (70 loc) · 2.37 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import asyncio
from datetime import datetime
import uvicorn
import websockets
from fastapi import FastAPI, Depends
from fastapi import HTTPException
from fastapi.exceptions import RequestValidationError
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse
from controller import notice, websocket, message
from utils.times import getMsTime
app = FastAPI()
app.include_router(websocket.ws_router, prefix="/ws")
app.include_router(notice.notice_router, prefix="/notice")
app.include_router(message.message_router, prefix="/message")
origins = [
"*"
]
headers = {"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "POST,OPTIONS,GET,UPDATE,DELETE"}
@app.exception_handler(HTTPException) # 自定义HttpRequest 请求异常
async def http_exception_handle(request, exc):
response = JSONResponse({
"code": exc.status_code,
"message": str(exc.detail),
"data": None,
"timestamp": getMsTime(datetime.now())
}, status_code=exc.status_code, headers=headers)
return response
@app.exception_handler(RequestValidationError)
async def request_validatoion_error(request, exc):
try:
message = str(exc.detail)
except:
try:
message = str(exc.raw_errors[0].exc)
except:
message = "请求错误"
response = JSONResponse({
"code": 400,
"message": message,
"data": None,
"timestamp": getMsTime(datetime.now())
}, status_code=400, headers=headers)
return response
@app.exception_handler(Exception)
async def request_validatoion_error(request, exc):
try:
message = str(exc)
except:
message = None
response = JSONResponse({
"code": 500,
"message": "内部错误",
"data": message,
"timestamp": getMsTime(datetime.now())
}, status_code=500, headers=headers)
return response
# 添加CORS中间件
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # 允许的源列表
allow_credentials=True, # 允许返回 cookies
allow_methods=["*"], # 允许所有 HTTP 方法
allow_headers=["*"], # 允许所有 HTTP 头
)
def main():
uvicorn.run(app, host="127.0.0.1", port=8000, ssl_keyfile="./.cert/key.pem", ssl_certfile="./.cert/cert.pem")
if __name__ == "__main__":
main()