2
votes

So I a new to the whole web and Flask programming. I was moving along pretty good displaying information from my database in web pages then I mixed a little bit of java script in. But then because of what I have been reading on the internet I got the idea to organize my URLs like so

  • localhost:5000/data/daily
  • localhost:5000/data/weekly
  • localhost:5000/data/monthly

However when I make my URLs more then one level deep when flask pulls up the page I end up getting java script errors because these extra levels have been append to my src attribute path in my script tags.

So what is going on here? Is there just some basic tid bit of web programming knowledge I am missing? I added some code bits below that shows example of what I am encountering.

The files below are in the following folder configuration

project_root
├── app.py
├── static
│   └── js
│       └── clock.js
└── templates
    ├── clock.html
    └── index.html

app.py

import flask

app = flask.Flask(__name__)

@app.route('/clock')
def clock():
    return flask.render_template('clock.html')

@app.route('/deep/clock')
def deep_clock():
    return flask.render_template('clock.html')

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

clock.html

<!DOCTYPE html>
<html>

<head>
    <script src="static/js/clock.js"></script>
</head>
<body onload="startTime()">

<div id="txt"></div>

</body>
</html>

clock.js

function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}

So if you copy everything and run the app.py then

  • localhost:5000/deep/clock will fail

and

  • localhost:5000/clock works

So what is going on here? What do I need to do to get them both to work in the current configuration?

1

1 Answers

3
votes

when you run the app, you should see the log says:

127.0.0.1 - - [18/Nov/2015 11:00:40] "GET /clock HTTP/1.1" 200 -
127.0.0.1 - - [18/Nov/2015 11:00:40] "GET /static/js/clock.js HTTP/1.1" 200 -
127.0.0.1 - - [18/Nov/2015 11:00:52] "GET /deep/clock HTTP/1.1" 200 -
127.0.0.1 - - [18/Nov/2015 11:00:52] "GET /deep/static/js/clock.js HTTP/1.1" 404

As you can see, the LAST log says 404(NOT FOUND): it can't find the clock.js under /deep/static/js/. That's true, we don't have that folder at all.

so, the problem is the js path. The solution is:

change your js path from:

<script src="static/js/clock.js"></script>

to

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

now, everything should be good now :) with the help of this one, we can find our file successfully.


The documentation: Static Files