静态页面的 404 错误(Flask 框架)

Error 404 with static pages (Flask Framework)

我学习了很多教程并且一切正常。但是我启动了自己的网站,但只收到错误 404 not found。

我下载了一个 HTML 模板并设法将文件从 Github 克隆到 PythonAnywhere。现在我的文件结构是: Screenshot

Flask_app.py代码:

from flask import Flask

# set the project root directory as the static folder, you can set others.
app = Flask(flask_app, static_url_path='/home/dubspher/mysite')

app = Flask(__name__)
@app.route('/home/dubspher/mysite/')
def static_file(path):
    return app.send_static_file(index.html)

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

我应该使用模板创建另一个网站并使用 render_template 还是我可以使用 flask 请求静态页面?

到目前为止,我尝试了很多代码,但我不知道如何处理 static_url_path

HTML 如果需要:https://www.pythonanywhere.com/user/dubspher/shares/db715c9b9d7c43b7beb4245af23fb56c/

如果我需要添加更多信息,请告诉我。

这是您的代码,用于在您网站的根目录中提供 index.html(例如 http://example.com/):

from flask import Flask

# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_folder='/home/dubspher/mysite/')

@app.route('/')
def static_file():
    return app.send_static_file('index.html')

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

假定您的 /home/dubspher/mysite 目录中有一个 index.html 文件。

要跟进您的 css 问题,您可以通过将 static_url_path 传递给 Flask 构造函数来让 Flask 一般提供静态文件。当你这样做时,任何匹配 static_url_path flask 的请求都会被视为静态文件并根据 static_folder 路径提供它。在下面的示例中,我将 static_url_path 设置为静态,将 static_folder 设置为 /home/dubspher/mysite/。当对 http://example.com/static/css/site.css 的请求进入 flask 时,将提供文件 /home/dubspher/mysite/css/site.css.

from flask import Flask

app = Flask(__name__, static_url_path="/static", static_folder='/home/dubspher/mysite/')

@app.route('/')
def static_file():
    return app.send_static_file('index.html')

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

下面是引用 /home/dubspher/mysite/css/site.css 来自 index.html.

的样式表的示例
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/css/site.css">
</head>
<body>
Hello There
</body>
</html>

如果您确实使用 static_url_path,则需要非常小心,确保 static_folder 路径下的所有内容都是您希望访问的内容。 Flask 将按原样提供。