1515 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
1616"""
1717import os
18+ from pathlib import Path
1819
19- from django .http import HttpResponse ,HttpResponseRedirect
20+ from django .http import HttpResponse , HttpResponseRedirect
21+ from django .templatetags .static import static as _static
2022from django .urls import path , re_path , include
2123from django .views import static
2224from drf_spectacular .views import SpectacularAPIView , SpectacularRedocView , SpectacularSwaggerView
@@ -82,6 +84,22 @@ def get_index_html(index_path):
8284 return content
8385
8486
87+ def get_all_files (directory ):
88+ base_path = Path (directory )
89+ file_paths = [
90+ '/' + str (file .relative_to (base_path )).replace ('\\ ' , '/' )
91+ for file in base_path .rglob ('*' )
92+ if file .is_file ()
93+ ]
94+ return sorted (file_paths , key = len , reverse = True )
95+
96+
97+ static_dict = {
98+ chat_ui_prefix : get_all_files (os .path .join (PROJECT_DIR , 'apps' , "static" , 'chat' )),
99+ admin_ui_prefix : get_all_files (os .path .join (PROJECT_DIR , 'apps' , "static" , 'admin' ))
100+ }
101+
102+
85103def page_not_found (request , exception ):
86104 """
87105 页面不存在处理
@@ -91,21 +109,29 @@ def page_not_found(request, exception):
91109 if request .path .startswith (chat_ui_prefix + '/api/' ):
92110 return Result (response_status = status .HTTP_404_NOT_FOUND , code = 404 , message = "HTTP_404_NOT_FOUND" )
93111 if request .path .startswith (chat_ui_prefix ):
112+ in_ = [url for url in static_dict .get (chat_ui_prefix ) if request .path .endswith (url )]
113+ if len (in_ ) > 0 :
114+ a = admin_ui_prefix + in_ [0 ]
115+ return HttpResponseRedirect (_static (a ))
94116 index_path = os .path .join (PROJECT_DIR , 'apps' , "static" , 'chat' , 'index.html' )
95117 content = get_index_html (index_path )
96118 content .replace ("prefix: '/chat'" , f"prefix: { CONFIG .get_chat_path ()} " )
97119 if not os .path .exists (index_path ):
98120 return HttpResponse ("页面不存在" , status = 404 )
99121 return HttpResponse (content , status = 200 )
100122 elif request .path .startswith (admin_ui_prefix ):
123+ in_ = [url for url in static_dict .get (admin_ui_prefix ) if request .path .endswith (url )]
124+ if len (in_ ) > 0 :
125+ a = admin_ui_prefix + in_ [0 ]
126+ return HttpResponseRedirect (_static (a ))
101127 index_path = os .path .join (PROJECT_DIR , 'apps' , "static" , 'admin' , 'index.html' )
102128 if not os .path .exists (index_path ):
103129 return HttpResponse ("页面不存在" , status = 404 )
104130 content = get_index_html (index_path )
105131 content = content .replace ("prefix: '/admin'" , f"prefix: '{ CONFIG .get_admin_path ()} '" )
106132 return HttpResponse (content , status = 200 )
107133 else :
108- return HttpResponseRedirect (admin_ui_prefix + '/' )
134+ return HttpResponseRedirect (admin_ui_prefix + '/' )
109135
110136
111137handler404 = page_not_found
0 commit comments