瓶静态文件给予404

问题描述:

守则main.py文件:

from flask import Flask, render_template, send_from_directory 
app = Flask(__name__, static_url_path="") 
app._static_folder = "static" 

@app.route("/") 
def root(): 
    return app.send_static_file("index.html") 

@app.route("/about") 
def about(): 
    return app.send_static_file("about/index.html") 

@app.route("/projects") 
def projects(): 
    return app.send_static_file("projects/index.html") 

#snip 

if __name__ == "__main__": 
    app.run(host="0.0.0.0") 

当我去到根目录或​​目录它工作正常,但是当我尝试去/projects目录,我得到了错误:瓶静态文件给予404

错误消息:

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

+0

是否存在'projects/index.html'?它是否可读?从flask目录中尝试'python -c'print(open(“projects/index.html”)。read())'',看它是否打印出你期望的内容。 –

+0

@ChristianTernus是的,当我这样做的时候它打印的很好 – connorb08

+0

你可能在'[snip]'的某个地方有'projects'的另一个定义吗? –

有两个可能的原因。

  1. 您错误地输入了路径。您是否在projects(即project)或index.html中有错字?
  2. 该路径不存在。与render_template不同,如果路径不存在,则app.send_static_file就会死亡。由于static_folderstatic,因此项目页面代码应存在static/projects/index.html(而不是projects/index.html)。

要测试它是否为流氓问题,请使用return 'some string'替换项目视图的正文。如果该字符串没有显示,那么你的手上就有一只不同的野兽。如果是这样,那么它肯定是我上面确定的两个错误中的一个。

在一个不相关的说明中,我会将debug=True添加到app.run(...) kwargs列表中,以使开发更方便。 (只要有文件保存,应用程序就会刷新)

+0

路径绝对在那里。它可以在我的本地机器上运行,但是当我将这些文件复制到我的服务器上时,除了项目,其他所有的工作都可以正常工作。该页面的目录是/static/projects/index.html。当我尝试返回一个字符串时,它不显示,所以这可能是它。我将如何去解决这个问题? – connorb08

+0

我发现我的问题。当我输入'[website]/projects'时,它会自动将它变成'[website]/projects /',然后返回一个404错误。我不知道为什么会发生这种情况,但我通过将@ app.route(“/ projects”)更改为'@ app.route(“/ projects /”) – connorb08