0

I have the following Flask app, and I am trying to load a js file from a template:

from flask import Flask, request, send_from_directory, render_template

# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

@app.route("/")
def main():
    return render_template('index.html')

if __name__ == "__main__":
    app.run()

Here is the folder:

enter image description here

My index.html file does load but the js doesn't:

<head>
    <script src="/static/js/asynckittens.js"></script>
</head>



  hello world

I have tried it as /js/asynckittens.js, and even /asynckittens.js and nothing will load this file. How can I load a js file in a basic flask server?

halfer
  • 19,824
  • 17
  • 99
  • 186
codyc4321
  • 9,014
  • 22
  • 92
  • 165
  • Did you get any error? –  Feb 26 '21 at 02:21
  • Loading failed for the – codyc4321 Feb 26 '21 at 02:22
  • Does this answer your question? [How to serve static files in Flask](https://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask) – Jake Jackson Feb 26 '21 at 13:44
  • no thats the link i'm using it isn't working – codyc4321 Feb 26 '21 at 15:28
  • Note that we prefer a technical style of writing here. We gently discourage greetings, hope-you-can-helps, thanks, advance thanks, notes of appreciation, regards, kind regards, signatures, please-can-you-helps, chatty material and abbreviated txtspk, pleading, how long you've been stuck, voting advice, meta commentary, etc. Just explain your problem, and show what you've tried, what you expected, and what actually happened. – halfer Feb 27 '21 at 19:45

2 Answers2

2

This question is possibly a duplicate of How to serve static files in Flask.

Flask is a great framework for developing web apps but its purpose is not to deploy(serve) web apps.

For that, you need a server(ngnix, apache etc)

2

For some reason, I had to delete the route serving js for flask to find these files:

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

I'm not sure why deleting that made it work but it did

codyc4321
  • 9,014
  • 22
  • 92
  • 165