【问题标题】:Error 404 with static pages (Flask Framework)静态页面出现错误 404(Flask 框架)
【发布时间】:2017-11-04 12:00:37
【问题描述】:

我学习了很多教程,一切正常。但是我创建了自己的网站,却只得到错误 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 还是有一种方法可以使用烧瓶请求静态页面?

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

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

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

【问题讨论】:

  • 是的,这段代码直接来自这个页面。
  • @app.route 定义了 flask 将在请求中寻找的 url 路径。那你要什么网址?您必须请求 yoursite.com/home/dubspher/mysite 才能访问您的索引页面。这是你要求的还是你要求yoursite.com?如果是后者,你希望你的路由被定义为@app.root('/')。此外,index.html 需要用引号引起来。
  • 我应该用 flask_app.py 更改 app = Flask(name) 吗?我看不到任何 wsgi 或 init 文件,这是部署静态页面的问题吗?
  • 有时我也会收到 500 Internal Server Error

标签: python flask pythonanywhere


【解决方案1】:

您的代码已修复,可在您网站的根目录中提供 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 烧瓶匹配的任何请求都将视为静态文件并根据 static_folder 路径提供它。在下面的示例中,我将 static_url_path 设置为 static,将 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()

这是一个从 index.html 引用 /home/dubspher/mysite/css/site.css 中的样式表的示例。

<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 将按原样提供。

【讨论】:

  • 太棒了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 2015-02-09
  • 2014-07-20
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
相关资源
最近更新 更多