where to keep js files in Flask applications?

牧云@^-^@ 提交于 2020-12-30 02:12:30

问题


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())

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>

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?


回答1:


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>

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")

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

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

Hope it helps.




回答2:


I just solved it by adding two more @app.route to app.py which serves the files angular.js and app.js respectively. And I used those routes in . But I don't feel that it's the right way to do this. I don't know.



来源:https://stackoverflow.com/questions/18909032/where-to-keep-js-files-in-flask-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!