![](/img/trans.png)
[英]Python Flask serving static files from root static folder rather than blueprint's static folder
[英]python flask - serving static files
我正在尝试使用 flask 提供 static 文件。 我不知道如何使用 url_for function。 我所有生成动态内容的路由都工作正常,我已经导入了 url_for,但是当我有这个代码时:
@app.route('/')
def home():
return url_for('static', filename='hi.html')
连同位于目录 static 中的我的“hi.html”文件(其中包含一些基本的 html),我在加载页面时得到的实际上是这样的:
/静态/hi.html
我只是错误地使用了 url_for 吗?
url_for
只返回该文件的URL。 听起来您想要redirect
到该文件的URL。 相反,您只是将URL的文本作为响应发送到客户端。
from flask import url_for, redirect
@app.route('/')
def home():
return redirect(url_for('static', filename='hi.html'))
您正在获得正确的输出。 url_for
为您提供的参数生成url 。 在您的情况下,您将在static
目录中生成hi.html
文件的URL 。 如果你想实际输出文件,你会想要
from flask import render_template, url_for
...
return render_template(url_for("static", filename="hi.html"))
但此时,您的静态目录需要位于templates目录下(无论何时配置为live)。
如果您要提供这样的静态html文件,那么我的建议是通过直接从您的Web服务器将流量路由到/static/.*
来在烧瓶应用程序之外提供它们。 使用nginx或apache在网上有很多例子。
如今, /static/
中的文件是自动提供的,并且仅使用url_for
引用。
但是有send_from_directory
- 看到这个很好的答案: https://stackoverflow.com/a/20648053
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.