1

I'm just starting out with Flask, and I was wondering what the best method for dealing with how flask deals with static files when trying to use a premade CSS template.

Basically, I have downloaded a CSS template that I liked off the internet, but when if I simply drag the files into my flask application folder the CSS, JS, and image files do not work since they are not located in the static folder.

But if I move all the static files into the static folder, then I have to go through all the code and change the link urls, which is very time consuming.

The CSS Template I am using has an index.html that uses links like

<link rel = "stylesheet" href = "css/style.css" >

I have set both the static_folder = "" and the static_url_path = "" in my flask app and I have moved the css, js, and image folders from the downloaded template into the base folder for the application, but the links are still not working.

Is there a better way to deal with using premade CSS templates with flask? Can I override the need to put css and js and image files in the static folder somehow? Thanks for your help!

2
  • Look at Flask class constuctor link . The are optional parameters static_path Commented Mar 23, 2016 at 7:10
  • Changing the static path to "css" is probably a bad idea if you want to serve different static files later like Js or JSON. I would rewrite every template and use <link rel="stylesheet" href="{{ url_for('static', filename='css/common.css') }}"> which is the standart way for flask apps. Commented Mar 23, 2016 at 12:47

1 Answer 1

1

(Sorry for opening this old post, but I'm on a badge hunt :])

There are several possible solutions, but the one I would recommend is to move the file style.css to folder <server_root>/static/css/.

Then create the flask app like app = Flask(__name__, static_url_path=''), what means that it still serves static files from the static/ folder, but on path / (so <server_root>/static/css/style.css is served on /css/style.css).

With this setup, your links href="/css/style.css" will work.


However, it's strongly recommended to use flask.url_for('endpoint', param='value') instead of /endpoint/url/value both in code and templates (surrounded with {{ ... }}) for all URLs - static files ('static', filename='css/style.css') and your own endpoints. So if your endpoint looks like this,

@app.route('/some/path/<variable>')
def some_endpoint(variable):
    # do something and return response...

... you can use url_for('some_endpoint, variable='something') no matter what the actual URL (/some/path/something/ in this case) is. (Tested python 3.6.7; flask 1.0.2)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.