Latest Version: 0.9.6.1

PylonsApp subclass for functions with no globals by Ben Bangert


Language: Python
Tags: routes, async
 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
70
71
72
73
# Mostly the same as the prior callable routing, except in middleware.py
from routes import request_config
import types

def eat_blank_iters(app_iter, response, environ, start_response):
    content_written = False
    del response.headers['Content-Length']
    while True:
        try:
            content = app_iter.next()
        except:
            if hasattr(app_iter, 'close'):
                app_iter.close()
            content_written = True
            break
        if content and not content_written:
            start_response(response.status, response.headerlist)
            yield content
        elif content:
            yield content
    if not content_written:
        start_response(response.status, response.headerlist)
        yield ''
    raise StopIteration

class MyApp(PylonsApp):
    def resolve(self, environ, start_response):
        # Update the Routes config object in case we're using Routes
        config = request_config()
        config.redirect = self.redirect_to
        match = environ['wsgiorg.routing_args'][1]
        
        environ['pylons.routes_dict'] = match
        controller = match.get('func')
        if not controller:
            # Use existing lookup scheme if no classname is around
            controller = match.get('controller')
            if not controller:
                return
            else:
                return self.find_controller(controller)

        if self.log_debug:
            log.debug("Resolved URL to controller: %r", controller)
        return controller
    
    def dispatch(self, controller, environ, start_response):
        match = environ['wsgiorg.routing_args'][1]
        
        # Assume we're doing a single function if we have a func
        if 'func' in match:
            ctx = environ['pylons.pylons']
            response = controller(ctx)
            if isinstance(response, types.GeneratorType):
                return eat_blank_iters(response, ctx.response, environ, start_response)
            else:
                del ctx.response.headers['Content-Length']
                ctx.response.headers['Content-Length'] = len(response)
                start_response('200 OK', ctx.response.headers.items())
                return [response]
        else:
            return PylonsApp.dispatch(self, controller, environ, start_response)


# and routing.py now hooks up like so:
    map.connect('hello/:action', func=hello.hello, action='index')


# and the function 'hello' in the controllers/hello.py module:
def hello(ctx):
    yield ''
    yield 'hello world,'
    yield ' the environ is %s' % ctx.request.environ

Top