在Flask应用程序中将js文件保存在哪里? [英] where to keep js files in Flask applications?

查看:56
本文介绍了在Flask应用程序中将js文件保存在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to flask and using it to serve index.html at "localhost:5000/". Currently I have only 3 files: index.html, angular.js, and app.js; and all of them are in same folder. I am serving index.html as :

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

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

I want to include angular.js and app.js in index.html. I tried this :

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

但是它不同时包含这两个文件(我从查看页面源代码"中检查了这两个文件).flask是否从中获取包含文件的默认目录?我应该如何实现?

But it is not including both the files (which I checked from 'view page source'). Is there a default directory from where flask takes included files? How should I achieve this?

推荐答案

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

Flask should know the path from where it can serve static files. Create 'static' directory put all static files in it. And, in index.html use:

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

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

Note that there is special endpoint called 'static' which looks into directory called 'static' and serves that file. You can also change name of the static directory.

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

此外,创建一个名为"templates"的目录,并在其中复制所有html文件,并在方法内部使用render_template方法,如下所示:

Also, create directory called "templates" and copy all your html files in there and use render_template method inside your method as:

return render_template("index.html")

因此,您的目录结构应类似于:

So, your directory structure should look like:

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

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

希望有帮助.

这篇关于在Flask应用程序中将js文件保存在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆