Latest Version: 0.9.6.1

PylonsApp subclass for callable routing by Ben Bangert


Language: Python
Tags: routes
 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
# This patch, lets you setup routes like so in addition to normal style
# NOTE: This requires the latest development tip of Routes and Pylons

map.connect('hello/:action', callable=hello.Hello, action='index')

# For example, in routing.py:

import helloworld.controllers.hello as hello

def make_map():
    """Create, configure and return the routes Mapper"""
    map = Mapper(directory=config['pylons.paths']['controllers'],
                 always_scan=config['debug'])
    map.connect('error/:action/:id', controller='error')
    
    # CUSTOM ROUTES HERE
    map.connect('hello/:action', callable=hello.Hello, action='index')
    map.connect('bye/:action', callable=hello.Bye, action='index')



# Then inside controllers/hello.py
import logging

from pylons import request, response, session
from pylons import tmpl_context as c
from pylons.controllers.util import abort, redirect_to, url_for

from helloworld.lib.base import BaseController, render
#import helloworld.model as model

log = logging.getLogger(__name__)

class Hello(BaseController):
    def index(self):
        return 'Hello World'

class Bye(BaseController):
    def index(self):
        return 'Bye World'


# And inside of config/middleware.py:
# Add to imports
from routes import request_config

# Add class before make_app:
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('callable')
        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

# And inside make_app, replace PylonsApp() with:
    # My Pylons WSGI app
    app = MyApp()

Top