解决 Flask 注册蓝图时 templates 或 static 静态文件访问 404 的问题

  • 首先项目结构如下
myproject/
    app.py
    model1/
        buleprint.py
        templates/
            index.html
        static/
            css/
                style.css
            img/
                loading.png
            js/
                bootstrap.js
    model2/
        buleprint.py
        templates/
        static/
  • app.py:
from flask import Flask
from model1.buleprint import bp as b1
from model2.buleprint import bp as b2

app = Flask(__name__)
# 注册蓝图
app.register_blueprint(b1, url_prefix='/model1')
app.register_blueprint(b2, url_prefix='/model2')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
  • model1/buleprint.py:
from flask import Blueprint, render_template

# 蓝图实例化
bp = Blueprint('bp1', __name__)

@bp.route('/index', methods=['GET', 'POST'])
def index():
    return render_template('index.html')
  • model2/buleprint.py:
from flask import Blueprint, render_template

# 蓝图实例化
bp = Blueprint('bp2', __name__)

@bp.route('/index', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

访问 http://127.0.0.1:5000/model1/index 或者 http://127.0.0.1:5000/model1/index 都是 error 404, templates not found。需要给蓝图指定 templatesstatic 的文件夹路径。即修改,

  • model1/buleprint.py:
bp = Blueprint('bp1', __name__,
    template_folder='templates',  # 指定蓝图加载的templates文件夹
    static_folder='static'  # # 指定蓝图加载的static文件夹
    )
  • model2/buleprint.py:
bp = Blueprint('bp2', __name__,
    template_folder='templates',  # 指定蓝图加载的templates文件夹
    static_folder='static'  # # 指定蓝图加载的static文件夹
    )

此时 index.html 能正常访问,但是 static 的静态文件还是访问 404。问题在于主应用 app 的 static 路径优先级会高于蓝图,应指定初始化app的static_folder = None

  • app.py:
from flask import Flask
from model1.buleprint import bp as b1
from model2.buleprint import bp as b2

app = Flask(__name__, static_folder=None)  # static_folder指定为空
# 注册蓝图
app.register_blueprint(b1)
app.register_blueprint(b2)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
  • model1/buleprint.py:
from flask import Blueprint, render_template

# 蓝图实例化
bp = Blueprint('bp1', __name__,
    template_folder='templates',  # 指定蓝图加载的templates文件夹
    static_folder='static'  # # 指定蓝图加载的static文件夹
    )

@bp.route('/model1/index', methods=['GET', 'POST'])
def index():
    return render_template('index.html')
  • model2/buleprint.py:
from flask import Blueprint, render_template

# 蓝图实例化
bp = Blueprint('bp2', __name__,
    template_folder='templates',  # 指定蓝图加载的templates文件夹
    static_folder='static'  # # 指定蓝图加载的static文件夹
    )

@bp.route('/model2/index', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

templates 和 static 静态文件都正常访问。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容