Dynamic Subdomain Handling in a Web App (Flask) [closed]

纵然是瞬间 提交于 2019-11-26 17:59:14

问题


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?


回答1:


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"



回答2:


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


来源:https://stackoverflow.com/questions/11021691/dynamic-subdomain-handling-in-a-web-app-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!