user3233758
user3233758

Reputation: 143

Subdomains with Flask?

How might I go about implementing subdomains for my website with Flask?

The documentation, though very good, isn't very clear at all about this. The subdomains need not to be dynamic, I am only going to be using 2 or 3 of my own choosing.

How would I route them? Is it possible to test them in the normal way? (served locally by Flask)

Upvotes: 12

Views: 9667

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159855

If all you want to do is handle having particular endpoints under a particular subdomain, you can just use the subdomain argument to @route:

app = Flask(__name__)
# In Flask 1.0
# app = Flask(__name__, subdomain_matching=True)

# Must add this until Flask 1.0
# Must be host:port pair or will not work
app.config["SERVER_NAME"] = "local.dev:5000"

@app.route("/")
def home():
    return "Sweet home"

@app.route("/some-route")
def some_route():
    return "on the default subdomain (generally, www, or unguarded)"

@app.route("/", subdomain="blog")
def blog_home():
    return "Sweet blog"

@app.route("/<page>", subdomain="blog")
def blog_page(page):
    return "can be dynamic: {}".format(page)

To handle development locally, you need to create entries in your hosts file to point these various domains to your machine:

local.dev    127.0.0.1
blog.local.dev    127.0.0.1

Then you can use local.dev and blog.local.dev rather than localhost to see your work.

Upvotes: 21

Related Questions