Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask : How to serve static files from under the template directory?

i use Flask and want to change my assets folder directory.Here's my folder structure:

/python
   /static
     /js
     /img
     /font
     /css
   /templates
     /default
       /css
       /js
       /img
   /venv
   app.py

I want to move all the folders under static folder (js,css,font,img) under to the folder default. But when i do this my css files and the others(js etc.) can not be loaded the page.Should i set a property to my application? I also tried this one:

app = Flask(__name__,static_path="/templates/default")

But could not make it.Is there another way to do this?Thanks a lot.

Update: When i remove the leading slash in the line above (static_path="templates/default") got this error ValueError: urls must start with a leading slash with the traceback:

Traceback (most recent call last):
  File "app.py", line 17, in <module>
    app = Flask(__name__,static_path="templates/default")
  File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 481, in __init__
    view_func=self.send_static_file)
  File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 63, in wrapper_func
    return f(self, *args, **kwargs)
  File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 943, in add_url_rule
    rule = self.url_rule_class(rule, methods=methods, **options)
  File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/werkzeug/routing.py", line 550, in __init__
    raise ValueError('urls must start with a leading slash')
ValueError: urls must start with a leading slash
like image 325
saidozcan Avatar asked Feb 22 '13 15:02

saidozcan


1 Answers

It should be static_folder not static_path while initializing app.

app = Flask(__name__,static_folder="/templates/default")

In templates:

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

Hope it helps.

like image 130
rajpy Avatar answered Nov 03 '22 01:11

rajpy