Dynamic Subdomain Handling in a Web App (Flask)

Bruce Collie picture Bruce Collie · Jun 13, 2012 · Viewed 17.5k times · Source

I'm going to be using flask to create a web application, and part of the application will involve a subdomain (for example, user1.appname.org).

I'm not sure how to go about creating these subdomains dynamically in the flask configuration, or how to deploy them to a production server.

What is the best way of doing this?

Answer

Sean Vieira picture Sean Vieira · Jun 14, 2012

All Flask's routing constructs support the subdomain keyword argument (this includes support for route variables).

@app.route("/", subdomain="static")
def static_index():
    """Flask supports static subdomains
    This is available at static.your-domain.tld"""
    return "static.your-domain.tld"

@app.route("/dynamic", subdomain="<username>")
def username_index(username):
    """Dynamic subdomains are also supported
    Try going to user1.your-domain.tld/dynamic"""
    return username + ".your-domain.tld"