Login

router view

Author:
tokibito
Posted:
January 19, 2010
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

simple routing views

 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
## exampleapp/views.py
import re
from django.http import Http404, HttpResponse
from django.utils.datastructures import SortedDict

class RouterView(object):
    def __init__(self):
        self.mapping = SortedDict()

    def register(self, *args):
        for regex, view_func in args:
            self.mapping[re.compile(regex)] = view_func

    def __call__(self, request, *args, **kwargs):
        for regex, view_func in self.mapping.items():
            if regex.match(request.path[1:]):
                return view_func(request, *args, **kwargs)
        # does not match
        raise Http404

def some_view(request):
    return HttpResponse('test')

## urls.py
from django.conf.urls.defaults import *
from exampleapp.views import RouterView, some_view

router = RouterView()
router.register(
    (r'^foo/', some_view),
)

urlpatterns = patterns('',
    (r'', router),
    (r'foo/bar/', router),
)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

diegueus (on January 20, 2010):

This is cool, but for a lot of web developers is a bad practice, IMHO i think is usefull for small websites

#

Please login first before commenting.