Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling with multiple domains in Flask

I want to implement structure in Flask, which can handle multiple domains. So when I type in browser "http://domain1.com/show/1", it actually executes function with routing like

@app.route('<string:domain>/show/<int:id>')
def show(domain = '', id = ''):
    return 'Domain is ' + domain + ', ID is ' + str(id)

And it is very important, the URL in client's browser should be still "http://domain1.com/show/1". And as I know, when using redirect in Flask, it changes url. How should I organise such structure? Thanks!

like image 721
user2065831 Avatar asked Feb 12 '13 18:02

user2065831


People also ask

Can flask handle multiple requests?

Flask applications are deployed on a web server, either the built-in server for development and testing or a suitable server (gunicorn, nginx etc.) for production. By default, the server can handle multiple client requests without the programmer having to do anything special in the application.

Can you use multiple decorators to route urls to a function in flask?

The decorator syntax is just a little syntactic sugar. This code block shows an example using our custom decorator and the @login_required decorator from the Flask-Login extension. We can use multiple decorators by stacking them.

What is __ init __ In flask?

the Flask application object creation has to be in the __init__.py file. That way each module can import it safely and the __name__ variable will resolve to the correct package. all the view functions (the ones with a route() decorator on top) have to be imported in the __init__.py file.


1 Answers

The request object already has a url_root parameter. Or you can use the Host header:

print request.url_root  # prints "http://domain1.com/"
print request.headers['Host']  # prints "domain1.com"

If you need to redirect within the application, url_root is the attribute to look at, as it'll include the full path for the WSGI application, even when rooted at a deeper path (e.g. starting at http://domain1.com/path/to/flaskapp).

It probably is better still to use request.url_for() to have Flask generate a URL for you; it'll take url_root into account. See the URL Building documentation.

like image 162
Martijn Pieters Avatar answered Oct 25 '22 19:10

Martijn Pieters