【问题标题】:Flask serves static files with different path after forward slash [duplicate]Flask在正斜杠后提供具有不同路径的静态文件[重复]
【发布时间】:2020-05-02 21:26:46
【问题描述】:

我正在尝试使用 Flask 访问页面,但未提供静态文件。

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

我在浏览器上得到了 hello.html 页面,但所有静态文件路径都已更改为 localhost:5000/hello/static... 但如果我改为:

@app.route('/hello')

正确提供静态文件。 因此,每当我有任何带有正斜杠的路由时,它都会更改正在提供的静态文件,即

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

静态文件将更改并在新路径下提供服务 localhost:5000/editFile/static/... Routes with / after makes all static files be searched with wrong paths

If no / is added after route then static files are loaded correctly

【问题讨论】:

    标签: flask routes


    【解决方案1】:

    您需要在这些路由前添加一个斜杠:

    @app.route('/hello')
    

    和:

    @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.%   
    

    【讨论】:

      【解决方案2】:

      如果你想在/hello/ 这样的路由之后添加斜线,那么当你访问静态文件时,你应该使用这个url_for('static',filename = 'file') 静态端点用于检索静态文件

      【讨论】:

        【解决方案3】:

        要引用静态文件夹中的文件,请在用于定位文件的 href 中包含前导“/”,即 href="/static/filename"。父帖子中观察到的行为发生在省略前导斜杠时,即 href="static/filename"

        【讨论】:

          猜你喜欢
          • 2012-06-07
          • 2019-12-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-19
          • 2017-03-16
          • 2012-11-16
          • 1970-01-01
          相关资源
          最近更新 更多