简体   繁体   中英

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.

I've followed the documentation and set the FREEZER_RELATIVE_URLS config option to True only when freezing the site. This functions correctly, replacing url_for with relative_url_for in the template engine.

How do I also get it to use relative_url_for in my Python code only when a config option is set?

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 .

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. Create a helper function that will pick which url function to call when it is called, rather than deciding at import time.

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. You can also replace the url_for function used in Jinja templates with this function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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