39

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?

Bruce Collie
  • 501
  • 1
  • 5
  • 4

2 Answers2

67

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"
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 3
    Will this work running on the Flask testing localhost server? – Bruce Collie Jun 30 '12 at 12:03
  • 3
    I'm also wondering if there's a way to test this locally. I've tried adding serveral entries to my hosts file., this doesn't seem to work. – Robert Massa Jul 01 '12 at 11:20
  • 1
    @sean How woud you do something similar for custom domains. A user signs up with subdomain.example.com and then adds a custom domain such as www.mygreatsite.com ? How would I handle access to this custom domain in a Flask route? – Raj May 07 '13 at 02:29
  • 1
    @Raj - that would depend on how you are setting up those custom domains. (Better to ask a separate question with more details about your setup.) – Sean Vieira May 07 '13 at 11:46
  • 1
    You should also be able to test this locally with a free service like xip.io by 37Signals – John Wheeler Jul 26 '13 at 00:57
  • Downvoter, care to explain so I can improve the answer? – Sean Vieira Dec 16 '15 at 02:12
  • @SeanVieira, do you have a boiler-plate for this setup somewhere. i need one. – s_mj Apr 11 '19 at 04:59
  • How does this work with class based views? – Mojimi Nov 06 '19 at 20:29
53

To complement Sean Viera's post, you also need to set the SERVER_NAME config variable.

Documentation: http://flask.pocoo.org/docs/config/#SERVER_NAME

The name and port number of the server. Required for subdomain support (e.g.: 'myapp.dev:5000') Note that localhost does not support subdomains so setting this to “localhost” does not help. Setting a SERVER_NAME also by default enables URL generation without a request context but with an application context.

To test locally you need to add entries to your hosts file, like this:

127.0.0.1       cvshark.local
127.0.0.1       robert.cvshark.local
127.0.0.1       www.cvshark.local
Georgy K
  • 255
  • 3
  • 10
Robert Massa
  • 4,345
  • 1
  • 32
  • 44