python sanic 如果我想实现 asset_bundles 目录下不存在的静态资源自动去 asset_bundles 下的所有子目录找同名文件全都找不到才返回404否则返回找到的文件怎么写
你可以使用 Sanic 的 StaticFiles 中间件来实现静态资源的处理。在创建 StaticFiles 中间件时,可以指定一个 fallback 参数,用于在请求的静态资源不存在时,执行自定义的查找逻辑。下面是一个示例代码:
from sanic import Sanic
from sanic.response import text
from sanic.static import StaticFiles
import os
app = Sanic("myapp")
app.static('/', './asset_bundles', fallback=StaticFilesFallback())
class StaticFilesFallback:
async def get_response(self, request, file_path):
full_path = os.path.join('./asset_bundles', file_path.lstrip('/'))
if os.path.exists(full_path):
return await request.app.static.get_response(request, file_path)
else:
for root, dirs, files in os.walk('./asset_bundles'):
if file_path in files:
full_path = os.path.join(root, file_path)
return await request.app.static.get_response(request, full_path[len('./asset_bundles/'):])
return text('404 Not Found', status=404)
if __name__ == "__main__":
app.run()
这里我们创建了一个名为 StaticFilesFallback 的类,实现了 get_response 方法。这个方法的参数包括 request 和请求的静态资源路径 file_path。首先,我们检查请求的路径是否存在于 asset_bundles 目录下,如果存在,则直接返回相应的静态资源。否则,我们遍历 asset_bundles 目录下的所有子目录,查找是否有同名的文件。如果找到了,则返回相应的静态资源;否则,返回 404。
最后,我们在创建 StaticFiles 中间件时,指定了上面定义的 StaticFilesFallback 类作为 fallback 参数。这样,当请求的静态资源不存在时,就会执行我们自定义的查找逻辑。
原文地址: https://www.cveoy.top/t/topic/ds6z 著作权归作者所有。请勿转载和采集!