首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >flask-assets append_path() catch-22

flask-assets append_path() catch-22
EN

Stack Overflow用户
提问于 2019-06-27 18:58:25
回答 1查看 58关注 0票数 0

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

代码语言:javascript
复制
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

代码语言:javascript
复制
    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

我使用不雅的代码绕过了22条军规,但想知道如何选择既适用于ASSETS_DEBUG = True也适用于Falseappend_path() url参数。

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-28 03:10:26

一种解决方案是为/loutilities/static创建路由,如下所示

代码语言:javascript
复制
# 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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56789521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档