0

我有一个包,其中包含我想在应用程序中重用的静态文件。基于https://webassets.readthedocs.io/en/latest/environment.html#webassets.env.Environment.load_path我想出了以下代码片段,用于每个应用程序__init__.py(共享包是loutilities):

with app.app_context():
    # js/css files
    asset_env.append_path(app.static_folder)
    # os.path.split to get package directory
    asset_env.append_path(os.path.join(os.path.split(loutilities.__file__)[0], 'tables-assets', 'static'))

但是当 时ASSETS_DEBUG = False,这会导致在包中找到的文件之一出现 ValueError 异常。(有关详细回溯,请参阅https://github.com/louking/rrwebapp/issues/366 - 这可能与https://github.com/miracle2k/webassets/issues/387有关)。

ValueError: Cannot determine url for /var/www/sandbox.scoretility.com/rrwebapp/lib/python2.7/site-packages/loutilities/tables-assets/static/branding.css

更改代码以使用现在可以正常工作的 url 参数ASSETS_DEBUG = False

    asset_env.append_path(os.path.join(os.path.split(loutilities.__file__)[0], 'tables-assets', 'static'), '/loutilities')

但是现在ASSETS_DEBUG = True,我看到文件无法在 javascript 控制台中加载

Failed to load resource: the server responded with a status of 404 (NOT FOUND) branding.css

使用如下不优雅的代码解决了 Catch-22,但想知道如何选择append_path() url对两者都适用的参数ASSETS_DEBUG = TrueFalse.

with app.app_context():
    # js/css files
    asset_env.append_path(app.static_folder)
    # os.path.split to get package directory
    loutilitiespath = os.path.split(loutilities.__file__)[0]
    # kludge: seems like assets debug doesn't like url and no debug insists on it
    if app.config['ASSETS_DEBUG']:
        url = None
    else:
        url = '/loutilities'
    asset_env.append_path(os.path.join(loutilitiespath, 'tables-assets', 'static'), url)
4

1 回答 1

0

一种解决方案是为 创造一条路线/loutilities/static,因此

# add loutilities tables-assets for js/css/template loading
# see https://adambard.com/blog/fresh-flask-setup/
#     and https://webassets.readthedocs.io/en/latest/environment.html#webassets.env.Environment.load_path
# loutilities.__file__ is __init__.py file inside loutilities; os.path.split gets package directory
loutilitiespath = os.path.join(os.path.split(loutilities.__file__)[0], 'tables-assets', 'static')

@app.route('/loutilities/static/<path:filename>')
def loutilities_static(filename):
    return send_from_directory(loutilitiespath, filename)

with app.app_context():
    # js/css files
    asset_env.append_path(app.static_folder)
    asset_env.append_path(loutilitiespath, '/loutilities/static')
于 2019-06-27T19:10:26.310 回答