To create unique Flask application instances for different subdomains (e.g., user1.example.com, user2.example.com), you can implement a custom WSGI dispatcher. This dispatcher inspects the HTTP_HOST environment variable to identify the subdomain and uses an application factory to instantiate the corresponding Flask app.
Implementation Pattern
- Use an Application Factory pattern to create new instances on demand.
- Implement a WSGI class that maintains a cache of instantiated applications to avoid repeated creation.
- Use
werkzeug.exceptions.NotFound if a requested subdomain does not map to a valid user/application to ensure a proper 404 response.
Note: This pattern requires the webserver to be configured to route all subdomains to your application.
from threading import Lock
from werkzeug.exceptions import NotFound
class SubdomainDispatcher:
def __init__(self, domain, create_app):
self.domain = domain
self.create_app = create_app
self.lock = Lock()
self.instances = {}
def get_application(self, host):
host = host.split(':')[0]
assert host.endswith(self.domain), 'Configuration error'
subdomain = host[:-len(self.domain)].rstrip('.')
with self.lock:
app = self.instances.get(subdomain)
if app is None:
app = self.create_app(subdomain)
self.instances[subdomain] = app
return app
def __call__(self, environ, start_response):
app = self.get_application(environ['HTTP_HOST'])
return app(environ, start_response)
# Usage example
def make_app(subdomain):
user = get_user_for_subdomain(subdomain)
if user is None:
return NotFound()
return create_app(user)
application = SubdomainDispatcher('example.com', make_app)