Flask 应用程序中的 js 文件保存在哪里?

2024-03-28

我是 Flask 的新手,并使用它在“localhost:5000/”处提供 index.html。目前我只有 3 个文件:index.html、angular.js 和 app.js;它们都在同一个文件夹中。我将 index.html 提供为:

@app.route('/')
def index():
    return make_response(open('index.html').read())

我想在index.html 中包含angular.js 和app.js。我试过这个:

<script src="angular.js"></script>
<script src="app_controller.js"></script>

但它不包括这两个文件(我从“查看页面源代码”中检查过)。 Flask 是否有一个默认目录来获取包含的文件?我应该如何实现这个目标?


Flask 应该知道它可以提供静态文件的路径。创建“static”目录,将所有静态文件放入其中。并且,在index.html中使用:

<script src="{{ url_for('static', filename='angular.js')}}"</script>

请注意,有一个名为“static”的特殊端点,它会查找名为“static”的目录并提供该文件。您还可以更改静态目录的名称。

app = Flask(__name__, static_folder="differet_dir_name")

另外,创建名为“templates”的目录并将所有 html 文件复制到其中,并在方法中使用 render_template 方法,如下所示:

return render_template("index.html")

因此,您的目录结构应如下所示:

app.py
static --> contains all static files
templates --> contains all html files

Links: http://flask.pocoo.org/docs/quickstart/#static-files http://flask.pocoo.org/docs/quickstart/#static-files http://flask.pocoo.org/docs/api/#application-object http://flask.pocoo.org/docs/api/#application-object

希望能帮助到你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flask 应用程序中的 js 文件保存在哪里? 的相关文章

随机推荐