使用Flask托管静态文件和模板文件很困难

时间:2018-11-25 20:23:07

标签: javascript python html css flask

我想使用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找不到我的模板和静态文件夹中的所有文件。

1 个答案:

答案 0 :(得分:0)

它们已经托管,您可以从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)