Flask: static files in subdirectories

In my flash drive template file, I include the css file (I commented on the template) as follows:

url_for('static', filename='css/bootstrap.css')

This means /static/css/bootstrap.css , which means (due to the leading slash) it is interpreted as domain.com/static/css/boostrap.css . Unfortunately, the actual static folder is located in a subdirectory: domain.com/projects/test/static/

Features of the environment:

My fcgi file located in the ~/fcgi-bin (depends on the specific node):

 $ cat ~/fcgi-bin/test.fcgi #!/usr/bin/env python2.7 import sys sys.path.insert(0, "/home/abcc/html/projects/test") from flup.server.fcgi import WSGIServer from app import app class ScriptNameStripper(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['SCRIPT_NAME'] = '' return self.app(environ, start_response) app = ScriptNameStripper(app) if __name__ == '__main__': WSGIServer(app).run() 

and my .htaccess located at domain.com/projects/test/

 $ cat .htaccess <IfModule mod_fcgid.c> AddHandler fcgid-script .fcgi <Files ~ (\.fcgi)> SetHandler fcgid-script Options +FollowSymLinks +ExecCGI </Files> </IfModule> <IfModule mod_rewrite.c> Options +FollowSymlinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /fcgi-bin/test.fcgi/$1 [QSA,L] </IfModule> 

To summarize, I want url_for('static', filename='css/bootstrap.css') return static/css/bootstrap.css instead of /static/css/bootstrap.css

EDIT # 1

I noticed that this happens with regular url_for calls not for static files like url_for ('about').

EDIT # 2

I wrote a quickstart-app and a blog post about this.

+8
python flask fastcgi url-for
source share
1 answer

Do not give the script name an empty string, try setting it to '/ projects / test'. By setting SCRIPT_NAME to an empty line, the application considers its work in the root of the domain, so the routes created by url_for will begin there. With the name of the script '/ projects / test', url_for('static', filename='/foo/bar.css') will return '/projects/test/static/foo/bar.css'

If you really want your applications with static media running on a different endpoint, you just need to execute the roll, something like this:

 from flask import Flask from os.path import join app = Flask(__name__) def url_for_static(filename): root = app.config.get('STATIC_ROOT', '') return join(root, filename) 
+5
source share

All Articles