【问题标题】:Flask serves static html pagesFlask 提供静态 html 页面
【发布时间】:2012-09-06 21:43:46
【问题描述】:

我正在通过 Flask 框架实现一个网络应用程序。这个 web 应用程序即将提供结构类似于 java doc 的静态 html 页面。

代码:

from flask import Flask, send_from_directory,url_for

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

@app.route("/report")
def view_report():
    url_for('static', filename='report/flexmonkey/html/')
    return send_from_directory('static', 'report/flexmonkey/html/index.html')

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

index.html:

<html xmlns:lxslt="http://xml.apache.org/xslt" xmlns:stringutils="xalan://org.apache.tools.ant.util.StringUtils">
<head>
<META http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Unit Test Results.</title>
</head>
<frameset cols="20%,80%">
<frameset rows="30%,70%">
<frame src="overview-frame.html" name="packageListFrame">
<frame src="allclasses-frame.html" name="classListFrame">
</frameset>
<frame src="overview-summary.html" name="classFrame">
<noframes>
<h2>Frame Alert</h2>
<p>
                This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
            </p>
</noframes>
</frameset>
</html>

目录结构:

~/workspace/testReport/static/report/flexmonkey/html $ ls
allclasses-frame.html  alltests-fails.html  automation  overview-frame.html    stylesheet.css
alltests-errors.html   all-tests.html       index.html  overview-summary.html

错误信息:

127.0.0.1 - - [13/Sep/2012 11:01:25] "GET /overview-frame.html HTTP/1.1" 404 -
127.0.0.1 - - [13/Sep/2012 11:01:25] "GET /allclasses-frame.html HTTP/1.1" 404 -
127.0.0.1 - - [13/Sep/2012 11:01:25] "GET /overview-summary.html HTTP/1.1" 404 -

【问题讨论】:

  • 我建议实际上添加一个问题,以便人们知道您在寻求什么帮助。大概,您希望有人告诉您为什么会出现这些错误,但这并不是很清楚。您是否尝试过在send_from_directory 中使用不同的目录?似乎问题可能只是您提供的路径不太正确。也许它需要是绝对的?
  • Armin Ronacher 说“send_from_directory 的相对路径是相对于应用程序根文件夹的”。 flask.pocoo.org/mailinglist/archive/2011/9/26/…

标签: html static web flask


【解决方案1】:

如果您只想提供静态文件,则无需使用 Flask。在您拥有 html 文件的目录中,输入 python -m SimpleHTTPServer 然后浏览 http://localhost:8000/

对于 Python 3,请键入 python -m http.server

【讨论】:

    【解决方案2】:

    默认情况下,flask 会将 /static 文件夹中的任何内容作为静态文件提供,除非重新定义为 app = Flask(__name__, static_url_path='some_other_folder')。因此,将所有 html 文件放在 static 文件夹下并运行一个简单的烧瓶服务器:

    from flask import Flask, send_from_directory
    
    app = Flask(__name__)
    
    @app.route('/')
    def root():
        return send_from_directory('','index.html') # serve root index.html
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=8080, debug=True)
    

    然后访问http://localhost:8080/static/report/flexmonkey/html/overview-summary.html,您应该会得到它。

    【讨论】:

      猜你喜欢
      • 2012-09-21
      • 1970-01-01
      • 2014-08-26
      • 2016-09-14
      • 1970-01-01
      • 2023-03-13
      • 2018-02-05
      • 2016-09-03
      • 1970-01-01
      相关资源
      最近更新 更多