Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

url_for within different Flask instances

Tags:

python

flask

wsgi

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

like image 404
free2use Avatar asked Nov 09 '22 17:11

free2use


1 Answers

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)
like image 75
free2use Avatar answered Nov 15 '22 13:11

free2use