codyc4321
codyc4321

Reputation: 9682

How to serve static file from static folder using Flask

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?

Upvotes: 0

Views: 10156

Answers (1)

codyc4321
codyc4321

Reputation: 9682

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

Upvotes: 2

Related Questions