根据网址请求呈现不同的静态文件夹

时间:2014-03-17 11:30:32

标签: static flask

使用Flask,我可以根据网址渲染不同的模板。例如:

这对jinja_loader和自定义Loader非常有用,但现在我已经坚持使用静态文件。

静态文件取决于模板,因此它们位于templates / static / site {0-9}中,但当然,我无法在static_folder参数上设置jinja_loader,因为它与Jinja无关但对于Flask。

如何根据当前网址呈现正确的静态文件夹?

例如,这里是加载的代码:

Flask(app_name,
        static_url_path = '/public',
        static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates/static')
    )

在templates / static中,我有:

static/
    site1/
        css/
        js/
        images/
    site2/
        css/
        js/
        images/
    etc...

2 个答案:

答案 0 :(得分:1)

您必须在static次观看中使用显式路径:

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

其中site1可以从request.path.split('/', 1)[0]获取:

url_for('static', filename='{}/css/...'.format(request.path.split('/', 1)[0]))

您可以创建自定义static视图:

from flask import request, send_from_directory, current_app, safe_join
import os.path

@app.route('/<site>/static/<path:filename>')
def per_site_static(site, filename):
    if site is None:
        # pick site from the URL; only works if there is a `/site/` first element.
        site = request.path.split('/')[0]
    static_folder = safe_join(current_app.static_folder, site)
    cache_timeout = current_app.get_send_file_max_age(filename)
    return send_from_directory(static_folder, filename,
                               cache_timeout=cache_timeout)

然后使用url_for()生成网址:

{{ url_for('per_site_static', site=None, filename='css/...') }}

答案 1 :(得分:0)

另一个有趣的替代方案如下:

class GenericStaticFlask(Flask):
    def send_static_file(self, filename):
        # g.site contains the name of the template path for siteX
        return super(GenericStaticFlask, self).send_static_file("%s/%s" % (g.site, filename))

app = GenericStaticFlask(app_name,
    static_url_path = '/public',
    static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates/static')
)