PageRenderTime 20ms CodeModel.GetById 14ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/circuits/web/dispatchers/virtualhosts.py

https://bitbucket.org/prologic/circuits/
Python | 59 lines | 34 code | 5 blank | 20 comment | 0 complexity | 73bf2d7e5841f131ec9106920bbe92a6 MD5 | raw file
 1# Module:   virtualhost
 2# Date:     13th September 2007
 3# Author:   James Mills, prologic at shortcircuit dot net dot au
 4
 5"""VirtualHost
 6
 7This module implements a virtual host dispatcher that sends requests
 8for configured virtual hosts to different dispatchers.
 9"""
10
11try:
12    from urllib.parse import urljoin
13except ImportError:
14    from urlparse import urljoin  # NOQA
15
16from circuits import handler, BaseComponent
17
18
19class VirtualHosts(BaseComponent):
20    """Forward to anotehr Dispatcher based on the Host header.
21
22    This can be useful when running multiple sites within one server.
23    It allows several domains to point to different parts of a single
24    website structure. For example:
25    - http://www.domain.example      -> /
26    - http://www.domain2.example     -> /domain2
27    - http://www.domain2.example:443 -> /secure
28
29    :param domains: a dict of {host header value: virtual prefix} pairs.
30    :type  domains: dict
31
32    The incoming "Host" request header is looked up in this dict,
33    and, if a match is found, the corresponding "virtual prefix"
34    value will be prepended to the URL path before passing the
35    request onto the next dispatcher.
36
37    Note that you often need separate entries for "example.com"
38    and "www.example.com". In addition, "Host" headers may contain
39    the port number.
40    """
41
42    channel = "web"
43
44    def __init__(self, domains):
45        super(VirtualHosts, self).__init__()
46
47        self.domains = domains
48
49    @handler("request", priority=1.0)
50    def _on_request(self, event, request, response):
51        path = request.path.strip("/")
52
53        header = request.headers.get
54        domain = header("X-Forwarded-Host", header("Host", ""))
55        prefix = self.domains.get(domain, "")
56
57        if prefix:
58            path = urljoin("/%s/" % prefix, path)
59            request.path = path