Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up static folder path in Flask

Tags:

python

flask

Seems like my static files aren't being served properly. This is what it looks like right now:

myApp
    __init__.py
    static
       img
       js
         bootstrap.min.js
       etc.

This is what my app config in my __init__.py looks like:

app = Flask(__name__, static_url_path="", static_folder="static")

This is the error:

127.0.0.1 - - [01/Dec/2014 13:12:01] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 -

As far as the url routing goes, no problems there, localhost/home routes to home, localhost/contact routes to contact, etc. But static files aren't being found :( Am I missing something?

NOTE: I'm hosting this on my Mac, purely local host

This is my __init__.py main method:

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

Running as:

python __init.py__
like image 624
Stupid.Fat.Cat Avatar asked Dec 01 '14 18:12

Stupid.Fat.Cat


People also ask

How do you set a static folder in Flask?

To reference the static files using the url_for() function, pass in the name of the directory – static in this case – and the keyword argument of filename= followed by your static file name. Flask automatically creates a static view that serves static files from a folder named static in your application's directory.

What is static folder in Flask?

Flask – Static Files Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application. A special endpoint 'static' is used to generate URL for static files.

What is a static folder?

Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files.


1 Answers

It looks like you are hardcoding to static file URLs. You tell Flask to server them with no URL prefix -- the default would have been /static -- but the log shows the request going to /static/js/bootstrap.min.js. You probably have something like the following in a template file.

<script src="/static/js/bootstrap.min.js"></script>

Instead, you should use url_for to create the URL for you. Change the above to

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

This will result in

<script src="/js/bootstrap.min.js"></script>
like image 196
dirn Avatar answered Oct 23 '22 07:10

dirn