summaryrefslogtreecommitdiff
path: root/tests/fake_packages/FakeApp.egg/fakeapp/apps.py
blob: cae7eba35fd885d61a69c39a5d448a292bfb5ea4 (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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
############################################################
## Apps
############################################################

def simple_app(response, environ, start_response):
    start_response('200 OK', [('Content-type', 'text/html')])
    return ['This is ', response]

def basic_app(environ, start_response):
    return simple_app('basic app', environ, start_response)

def make_basic_app(global_conf, **conf):
    return basic_app

def basic_app2(environ, start_response):
    return simple_app('basic app2', environ, start_response)
    
def make_basic_app2(global_conf, **conf):
    return basic_app2

############################################################
## Composits
############################################################

def make_remote_addr(loader, global_conf, **conf):
    apps = {}
    addrs = {}
    for name, value in conf.items():
        if name.startswith('app.'):
            apps[name[4:]] = loader.get_app(value, global_conf)
        elif name.startswith('addr.'):
            addrs[name[5:]] = value
    dispatcher = RemoteAddrDispatch()
    for name in apps:
        dispatcher.map[addrs[name]] = apps[name]
    return dispatcher

class RemoteAddrDispatch(object):
    def __init__(self, map=None):
        self.map = map or {}

    def __call__(self, environ, start_response):
        addr = environ['REMOTE_ADDR']
        app = self.map.get(addr) or self.map['0.0.0.0']
        return app(environ, start_response)

############################################################
## Filters
############################################################

def make_cap_filter(global_conf, method_to_call='upper'):
    def cap_filter(app):
        return CapFilter(app, global_conf, method_to_call)
    return cap_filter

class CapFilter(object):

    def __init__(self, app, global_conf, method_to_call='upper'):
        self.app = app
        self.method_to_call = method_to_call
        self.global_conf = global_conf

    def __call__(self, environ, start_response):
        app_iter = self.app(environ, start_response)
        for item in app_iter:
            yield getattr(item, self.method_to_call)()
        if hasattr(app_iter, 'close'):
            app_iter.close()