10
10
import sys
11
11
import time
12
12
import uvicorn
13
+ import mimetypes
13
14
14
15
from fastapi import FastAPI , Request , Path , Query
15
16
from fastapi .staticfiles import StaticFiles
16
17
from fastapi .exceptions import RequestValidationError
17
18
from starlette .middleware .cors import CORSMiddleware
18
- from starlette .responses import RedirectResponse
19
+ from starlette .responses import RedirectResponse , FileResponse
19
20
20
21
from .utils import gc , is_port_in_use , server_loger
21
22
from .rjson import ReJson
@@ -32,6 +33,8 @@ def gen_fastapi_app():
32
33
license_info = {"name" : "MIT License" ,
33
34
"url" : "https://github.com/xaoyaoo/PyWxDump/blob/master/LICENSE" })
34
35
36
+ web_path = os .path .join (os .path .dirname (os .path .dirname (__file__ )), "ui" , "web" ) # web文件夹路径
37
+
35
38
# 跨域
36
39
origins = [
37
40
"http://localhost:5000" ,
@@ -48,11 +51,13 @@ def gen_fastapi_app():
48
51
allow_headers = ["*" ], # 允许所有头
49
52
)
50
53
54
+ # 错误处理
51
55
@app .exception_handler (RequestValidationError )
52
56
async def request_validation_exception_handler (request : Request , exc : RequestValidationError ):
53
57
# print(request.body)
54
58
return ReJson (1002 , {"detail" : exc .errors ()})
55
59
60
+ # 首页
56
61
@app .get ("/" )
57
62
@app .get ("/index.html" )
58
63
async def index ():
@@ -63,10 +68,29 @@ async def index():
63
68
app .include_router (rs_api , prefix = '/api/rs' , tags = ['远程api' ])
64
69
app .include_router (ls_api , prefix = '/api/ls' , tags = ['本地api' ])
65
70
71
+ # 根据文件类型,设置mime_type,返回文件
72
+ @app .get ("/s/{filename:path}" )
73
+ async def serve_file (filename : str ):
74
+ # 构建完整的文件路径
75
+ file_path = os .path .join (web_path , filename )
76
+
77
+ # 检查文件是否存在
78
+ if os .path .isfile (file_path ):
79
+ # 获取文件 MIME 类型
80
+ mime_type , _ = mimetypes .guess_type (file_path )
81
+ # 如果 MIME 类型为空,则默认为 application/octet-stream
82
+ if mime_type is None :
83
+ mime_type = "application/octet-stream"
84
+
85
+ # 返回文件
86
+ return FileResponse (file_path , media_type = mime_type )
87
+
88
+ # 如果文件不存在,返回 404
89
+ return {"detail" : "Not Found" }, 404
90
+
66
91
# 静态文件挂载
67
- web_path = os .path .join (os .path .dirname (os .path .dirname (__file__ )), "ui" , "web" )
68
- if os .path .exists (os .path .join (web_path , "index.html" )):
69
- app .mount ("/s" , StaticFiles (directory = web_path ), name = "static" )
92
+ # if os.path.exists(os.path.join(web_path, "index.html")):
93
+ # app.mount("/s", StaticFiles(directory=web_path), name="static")
70
94
71
95
return app
72
96
0 commit comments