Flask为静态文件提供不同路径的服务。

问题描述 投票:0回答:1

我试图使用Flask访问一个页面,但静态文件没有被服务。

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

我在浏览器上得到了hello.html页面,但所有静态文件的路径都改成了 localhost:5000hellostatic...。但如果我改成。

@app.route('/hello')

静态文件就会被正确地提供服务 所以每当我有任何一个带有斜线的路由时 它就会改变静态文件的服务方式,比如说

@app.route('/editFile/<int:id>')

静态文件会改变,并在新路径下提供服务。localhost:5000editFilestatic...带后缀的路由会使所有静态文件被搜索到错误的路径。

如果在路由后添加no,那么静态文件就会被正确加载

flask routes
1个回答
0
投票

你需要给这些路由加上一个斜线。

@app.route('/hello')

and:

@app.route('/editFile/<int:id>')

这应该会得到预期的行为。

顺便说一下,如果你还在后面加了一个斜杠,比如说。

@app.route('/test/')

那么一个请求 /test/ 将返回响应,并请求 /test 将返回一个308重定向到 /test/:

$ curl http://localhost:5009/test/  
response%

$ curl -i http://localhost:5000/test
HTTP/1.0 308 PERMANENT REDIRECT
Location: http://localhost:5000/test/

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL:
<a href="http://localhost:5009/test/">http://localhost:5000/test/</a>.  If not click the link.%   

0
投票

如果你想在路径后面加上斜线,就像这样。/hello/ 那么当你访问静态文件时,你应该使用这个。url_for('static',filename = 'file')静态端点是用来检索静态文件的。

© www.soinside.com 2019 - 2024. All rights reserved.