简体   繁体   English

如何有条件地从Frozen-Flask导入relative_url_for

[英]How to import relative_url_for conditionally from Frozen-Flask

I'm creating a website using Flask that I want to freeze using Frozen-Flask , but also have the site run live. 我正在使用Flask创建一个网站,我想使用Frozen-Flask将其冻结,但该网站也可以运行。

I've followed the documentation and set the FREEZER_RELATIVE_URLS config option to True only when freezing the site. 我已按照文档进行操作 ,仅在冻结站点时才将FREEZER_RELATIVE_URLS配置选项设置为True This functions correctly, replacing url_for with relative_url_for in the template engine. 此功能正常,更换url_forrelative_url_for模板引擎。

How do I also get it to use relative_url_for in my Python code only when a config option is set? 仅当设置了配置选项时,如何才能在Python代码中使用relative_url_for

I guess I need something like: 我想我需要这样的东西:

if config['FREEZER_RELATIVE_URLS']:
    from flask_frozen import relative_url_for as url_for
else:
    from flask import url_for

However, if I try to access flask.current_app.config with the other imports in my views.py I get an error: RuntimeError: working outside of application context . 但是,如果我尝试用views.py的其他导入访问flask.current_app.config ,则会收到错误消息: RuntimeError: working outside of application context

You're trying to access current_app outside of a view, so there's no app context to tell Flask what current_app points to. 您正在尝试在视图外部访问current_app ,因此没有应用上下文可以告诉Flask current_app指向什么。 Create a helper function that will pick which url function to call when it is called, rather than deciding at import time. 创建一个辅助函数,该函数将选择在调用时调用哪个url函数,而不是在导入时确定。

from flask import current_app, url_for as live_url_for
from flask_frozen import relative_url_for

def url_for(endpoint, **values):
    if current_app.config['FREEZER_RELATIVE_URLS']:
        return relative_url_for(endpoint, **values)

    return live_url_for(endpoint, **values)

Use this url_for helper inside your views rather than the other two functions. 在视图内部而不是其他两个函数中使用此url_for帮助器。 You can also replace the url_for function used in Jinja templates with this function. 您也可以使用此函数替换Jinja模板中使用的url_for函数。

# during app creation
from helpers import url_for
app.add_template_global(url_for)
app.context_processor(lambda: {'url_for': url_for})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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