Flask带动态url_prefix的Blueprint静态文件查找异常解决问询
问题
当URL包含额外变量时,如何让Flask Blueprint的静态文件查找功能正常工作?
示例
当使用带动态url_prefix(<int:id>)的Blueprint时:
# /a/__init__.py : a_bp = Blueprint('a', __name__, url_prefix = '/a/<int:id>', template_folder = 'templates', static_folder = 'static', static_url_path = '/static' ) # /a/id/__init__.py : id_bp = Blueprint('id', __name__, url_prefix = '/<int:id>', template_folder = 'templates', static_folder = 'static', static_url_path = '/static' ) # 另外: a_bp.register_blueprint(id_bp) app.register_blueprint(a_bp)
在浏览器访问 a/1/static/index.js 时,会触发以下错误:TypeError: Blueprint.send_static_file() got an unexpected keyword argument 'id'
补充信息
简化后的文件目录结构:
app/ bp/ a/ static/ index.js templates/ index.html id/ static/ index.js templates/ index.html
解决方案
1. 脱离动态前缀设置静态URL路径
Blueprint默认的静态路由会把url_prefix里的动态参数传递给send_static_file方法,导致参数不匹配。可以直接给静态文件设置一个不包含动态变量的全局路径:
# 修改a_bp的配置 a_bp = Blueprint('a', __name__, url_prefix = '/a/<int:id>', template_folder = 'templates', static_folder = 'static', static_url_path = '/static/a' # 全局唯一的静态资源路径 )
之后访问静态文件直接用 /static/a/index.js,不需要带上动态的id参数,就能正常获取文件。
2. 自定义静态路由忽略动态参数
手动注册静态文件路由,接收但忽略动态参数:
from flask import send_from_directory import os @a_bp.route('/static/<path:filename>') def custom_static(filename, id=None): # 直接返回静态文件,不处理id参数 static_dir = os.path.join(a_bp.root_path, 'static') return send_from_directory(static_dir, filename)
这样访问 /a/1/static/index.js 时,id参数会被路由捕获但不使用,静态文件能正常返回。
3. 拆分静态资源到独立Blueprint
创建一个不带动态url_prefix的Blueprint专门处理静态资源,避免和动态路由冲突:
# 单独创建静态Blueprint static_a_bp = Blueprint('static_a', __name__, static_folder='bp/a/static', # 指向a模块的静态目录 static_url_path='/a/static' ) app.register_blueprint(static_a_bp)
之后访问 /a/static/index.js 即可直接获取对应静态文件,无需关联动态id参数。
内容的提问来源于stack exchange,提问作者kando
相关产品推荐
相关产品推荐

