404 issues trying to import js files in Flask

Issue

I’ve tried answers from other posts, but they are not working for me.

Folders are: (py code is in ‘art’, flask is run from there)

art
  static
    css
    html
    img
    js
      lib

Import in html is:

    <script src="{{url_for('static', filename='js/lib/jquery-3.4.1.slim.min.js')}}"> </script>
    <script src="{{url_for('static', filename='js/Main.js')}}"> </script>

Error from Flask run:

127.0.0.1 - - [25/Aug/2021 10:46:17] "GET /art HTTP/1.1" 200 -
127.0.0.1 - - [25/Aug/2021 10:46:17] "GET /%7B%7Burl_for('static',%20filename='/js/bin/jquery-3.4.1.slim.min.js')%7D%7D HTTP/1.1" 404 -
127.0.0.1 - - [25/Aug/2021 10:46:17] "GET /%7B%7Burl_for('static',%20filename='/js/Main.js')%7D%7D HTTP/1.1" 404 -

From the Safari Web Inspector:

Web Inspector

Thanks.

EDIT: .py code:

@app.route("/art")

def index():
  return """
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta http-equiv="Expires" content="-1">
        <title>CD Test</title>

        <script src="{{url_for('static', filename='/js/lib/jquery-3.4.1.slim.min.js')}}"> </script>
        <script src="{{url_for('static', filename='/js/Main.js')}}"> </script>
      </head>

      <body>
        <h2>CD Test.</h2>
        <hr>
        <table>
          <tr>
            <td><img id="Pic" src="url/xxx.jpg" onclick="openFullscreen()"></td>
          </tr>
        </table>
      </body>

    </html>
  """

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

Solution

This can not work. You can not return template tag (the pieces of code in {{ }}) directly. You have to render the template first. I suggest you go there for a quick tutorial/example on how to render a templates.

Answered By – Niko B

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published