python sanic 实现访问 asset_bundles 路径下的静态资源时自动去 asset_bundles 的所有子目录找同名文件全都找不到才返回404否则返回找到的文件
可以使用 Sanic 的静态文件处理器来实现这个功能。具体实现如下:
from sanic import Sanic
from sanic.response import file
from sanic.exceptions import NotFound
app = Sanic(__name__)
@app.route('/asset_bundles/<filename:path>')
async def asset_bundles_handler(request, filename):
asset_bundles_path = '/path/to/asset_bundles' # 设置 asset_bundles 的路径
# 查找同名文件
file_path = None
for root, dirs, files in os.walk(asset_bundles_path):
if filename in files:
file_path = os.path.join(root, filename)
break
# 如果找到了同名文件,则返回该文件
if file_path is not None:
return await file(file_path)
# 否则返回 404
raise NotFound('File not found')
在这个例子中,我们使用了 Sanic 的路由装饰器来定义了一个路由,该路由的路径为 /asset_bundles/<filename:path>,其中 path 参数表示可以包含斜杠的任何路径。在函数体中,我们首先定义了 asset_bundles 的路径,然后使用 os.walk 函数遍历该目录及其子目录,查找是否存在同名文件。如果找到了同名文件,则使用 Sanic 的 file 函数将该文件返回。如果找不到同名文件,则抛出 NotFound 异常,返回 404 错误。
原文地址: https://www.cveoy.top/t/topic/ds8P 著作权归作者所有。请勿转载和采集!