summaryrefslogtreecommitdiff
path: root/wsgitools/applications.py
blob: 9112e45fadcf5e52b0891998d0016fb4cbe5a488 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class StaticContent:
    """
    This wsgi application provides static content on whatever request it
    receives with method GET or HEAD (content stripped). If not present, a
    content-length header is computed.
    """
    def __init__(self, status, headers, content):
        """
        @type status: str
        @param status: is the HTTP status returned to the browser (ex: "200 OK")
        @type headers: list
        @param headers: is a list of (header, value) pairs being delivered as
                HTTP headers
        @type content: basestring
        @param content: contains the data to be delivered to the client. It is
                either a string or some kind of iterable yielding strings.
        """
        assert isinstance(status, str)
        assert isinstance(headers, list)
        assert isinstance(content, basestring) or hasattr(content, "__iter__")
        self.status = status
        self.headers = headers
        length = -1
        if isinstance(content, basestring):
            self.content = [content]
            length = len(content)
        else:
            self.content = content
            if isinstance(self.content, list):
                length = sum(map(len, self.content))
        if length >= 0:
            if  not [v for h, v in headers if h.lower() == "content-length"]:
                headers.append(("Content-length", str(length)))
    def __call__(self, environ, start_response):
        """wsgi interface"""
        assert isinstance(environ, dict)
        if environ["REQUEST_METHOD"].upper() not in ["GET", "HEAD"]:
            resp = "Request method not implemented"
            start_response("501 Not Implemented",
                           [("Content-length", str(len(resp)))])
            return [resp]
        start_response(self.status, self.headers)
        if environ["REQUEST_METHOD"].upper() == "HEAD":
            return []
        return self.content