我正在尝试使用flask来提供静态文件.我不知道如何使用url_for函数.生成动态内容的所有路由工作正常,我已导入url_for,但是当我有这个代码时:
@app.route('/')
def home():
return url_for('static', filename='hi.html')
Run Code Online (Sandbox Code Playgroud)
随着我的'hi.html'文件(其中有一些基本的html)坐在目录静态中,我加载页面时得到的字面意思是:
/static/hi.html
我只是错误地使用url_for吗?
Mic*_*ene 17
url_for只返回该文件的URL.听起来你想要redirect该文件的URL.相反,您只是将URL的文本作为响应发送到客户端.
from flask import url_for, redirect
@app.route('/')
def home():
return redirect(url_for('static', filename='hi.html'))
Run Code Online (Sandbox Code Playgroud)
您正在获得正确的输出. 为您提供的参数url_for生成url.在您的情况下,您正在为目录中的hi.html文件生成URLstatic.如果你想实际输出文件,你会想要
from flask import render_template, url_for
...
return render_template(url_for("static", filename="hi.html"))
Run Code Online (Sandbox Code Playgroud)
但此时,您的静态目录需要位于templates目录下(无论何时配置为live).
如果您要提供这样的静态html文件,那么我的建议是通过/static/.*直接从您的Web服务器路由流量来在烧瓶应用程序之外提供它们.使用nginx或apache在网上有很多例子.