【问题标题】:Difficulty with using Flask to host static and templates files难以使用 Flask 托管静态和模板文件
【发布时间】:2018-11-25 20:23:07
【问题描述】:

我想使用 Flask 框架在 app.py 中托管 3 个文件。这是它的样子。

Project
    ├── templates
    │   └── index.html
    ├── static
    │   ├── index.js
    │   └── style.css
    └── app.py

如何使用 Flask 框架在 app.py 中托管这些文件?这是我的尝试,但它给了我一个错误,当我运行app.py 服务器文件时无法访问该站点。

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index_html():
    return render_template('index.html')

@app.route('/index.js')
def index_js():
    return render_template('index.js')

@app.route('/style.css')
def style_css():
    return render_template('style.css')

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

这也是我的index.html中包含的内容

<script type="text/javascript" src="{{ url_for('static', filename='index.js') }}"></script>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">

还有一件事,当我检查页面并转到源代码时,我的 index.jsstyle.cssindex.html 文件都不在那里。这基本上意味着 app.py 找不到位于我的模板和静态文件夹中的那些文件。

【问题讨论】:

  • 我不明白你为什么这样做。 JS 和 CSS 不是模板,它们是静态文件。
  • 删除静态文件的路由。这些可能会干扰 Flask 原本会做的事情。

标签: javascript python html css flask


【解决方案1】:

它们已经被托管,您可以从 html 文件中访问它们,比如说:

index.html

<html>
<head>
<link rel="stylesheet" href="../static/style.css">
</head>
<body>
  <script src="../static/index.js"></script>
</body>
</html>

app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index_html():
    return render_template('index.html')


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

【讨论】:

    猜你喜欢
    • 2014-12-10
    • 2019-04-25
    • 1970-01-01
    • 2012-01-30
    • 2013-06-18
    • 1970-01-01
    • 2011-08-31
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多