简体   繁体   中英

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

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.

Sorry, I misread your original directory output. You need to put templates IN the static directory, as that's where Flask looks for static data by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM