python - 提供位于 Flask 蓝图文件夹下的静态文件

标签 python flask

我有一个包含模板和静态文件的 Flask 蓝图。模板呈现正确,但链接的 CSS 文件返回 404 未找到。如何提供位于蓝图文件夹下的静态文件?

app/
  __init__.py
  auth/
    __init__.py
    static/
      style.css
    templates/
      index.html
auth = Blueprint('auth', __name__, template_folder='templates')

@auth.route('/')
def index():
    return render_template('index.html')
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">

最佳答案

通过传递 static_folder 告诉蓝图它的静态文件夹在哪里,然后使用 url_for 生成蓝图上 static 路由的 url。 This is described in the docs.

auth = Blueprint('auth', __name__, template_folder='templates', static_folder='static')
url_for('auth.static', filename='style.css')

此解决方案仅在蓝图具有 url_prefix 时有效。根据文档:

However, if the blueprint does not have a url_prefix, it is not possible to access the blueprint’s static folder. This is because the URL would be /static in this case, and the application’s /static route takes precedence. Unlike template folders, blueprint static folders are not searched if the file does not exist in the application static folder.

在这种情况下,一种解决方案可能是将样式表放入主 static 目录。

关于python - 提供位于 Flask 蓝图文件夹下的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41484453/

相关文章:

python - 更新重复项的更快方法

python - SQL Alchemy 根据其他列的单元格中包含的值过滤行

flask-login不能在Blueprint对象中使用?

python - 在 RESTful Web 服务中,服务器需要很长时间才能响应是否可以接受?

python - 访问 flask 中的静态文件夹

Python : Get gtk. 从另一个小部件中选择 TreeView

python - 迭代一个按指数增长的巨大整数列表,其中指数为 1.5

python - Cherrypy:多处理

python - 在 Python 中将数组保存到光栅文件的最简单方法

templates - 为什么 Flask/OpenShift 下的 trim_blocks 和 lstrip_blocks 在在线测试时会产生不同的结果,而在本地测试时会产生不同的结果?