5
votes

I have complex flask application with several Flask instances dispatched by werkzeug middleware. And in such situation I have two questions related not actually with url_for, but with flask context management actually.

1) How do I create url from one application to another?

2) Main one - how do I create url for specific application with no app_context at all. For example i need to create some url on import time or from celery task. I tried to do wrapper over all application instances and redefine url_for like

def url_for(self, *args, **kwargs):
    with self.app.app_context():
        return url_for(*args, **kwargs)

but just received following error "Application was not able to create a URL adapter for request independent URL generation. You might be able to fix this by setting the SERVER_NAME config variable." Any suggestions?

Update: my solution for second problem was correct, just needed to add SERVER_NAME, but first one is still open

1
Did you ever find a solution? - Patrick Yan
I've ended building custom url_builder for each application and using its routes. There is no other way, flask provides no support at all for multi-app architecture =( - free2use
Any chance you could share a generalized version? - Patrick Yan

1 Answers

1
votes

I ended up creating separated url builder for each application

absolute_url_adapter = app.url_map.bind_to_environ({
    'wsgi.url_scheme': 'http',
    'HTTP_HOST': app.config['SERVER_NAME'],
    'SCRIPT_NAME': app.url_prefix,
    'REQUEST_METHOD': 'GET',
})

url_prefix - is url, by which dispatcher dispatches requests

Then in each application You use it like that

absolute_url_adapter.build('main.main', force_external=True)