Login

automatic urlpattern creator

Author:
sleytr
Posted:
August 5, 2009
Language:
Python
Version:
1.1
Score:
3 (after 3 ratings)

This method creates urlpatterns based on view functions that have 'request' as their first parameter. See docstring for details.

 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
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns,url
from types import FunctionType
from django.core.urlresolvers import RegexURLPattern


def urlmapper(view_path,*args,**kwargs):
    '''
    This method creates urlpatterns based on view functions that have 'request' as their first parameter.

    Usage:
        urlpatterns = urlmapper('path.to.views'[, custom_url_patterns][, url_prefix][, url_name_prefix][, slug_names][, int_names])

    3 types of url scheme can be created automaticaly:
        plain:
            http://.../list_articles/ >>> def list_articles(request):
        integer
            http://.../show_article/3565/ >>> def show_article(request, id):
        slug
            http://.../show_articel/title_of_article/ >>> def show_article(request, slug):

    ** Variable names should be listed in the related lists: (default values can be seen bellow)
            urlpatterns = urlmapper('path.to.views',slug_names=['my_slug_name']) >>> def show_article(request, my_slug_name)

    ** Custom url patterns can be appended just like normal patterns method:        
            urlpatterns += urlmapper('path.to.views',
                    url(r'^custom_url/(?P<custom_var_name>\d+)/$', view, name='custom_url_name'),
                    (r'^another_url/$', 'another_view'),
                    )
        note: These custom mapped views will be excluded from automapping.
        
    ** Urls can be prefixed with 'url_prefix' keyword parameter:
            urlpatterns = urlmapper('support.views',url_prefix='members/')

    ** Url pattern names can be prefixed with 'url_name_prefix' keyword parameter:
            urlpatterns = urlmapper('support.views',url_name_prefix='sup_')

    ** Keyword arguments should follow any possible custom urlpatterns:
            urlpatterns = urlmapper('path.to.views',
                    (r'^another_url/$', 'another_view'),url(r'^surl/$', vi,name='viii'),
                    url_prefix='members/',url_name_prefix='sup_')
        

    '''
    slug_names=kwargs.get('slug_names',['slug','key','name'])
    int_names=kwargs.get('int_names',['id','pk','no'])
    pfx=kwargs.get('url_name_prefix','')
    url_prefix=kwargs.get('url_prefix','')
    custom_urls=[type(u)==RegexURLPattern and u.callback or u[1] for u in args]
    ul=[]
    exec  'import %s as mdl' % view_path
    for name, obj in mdl.__dict__.iteritems():
        if hasattr(obj, 'view_func'):
            obj=obj.view_func
        elif hasattr(obj, '__closure__') and obj.__closure__:
            obj=obj.__closure__[0].cell_contents
        if type(obj)!=FunctionType or name in custom_urls: continue        
        fc=getattr(obj,'func_code')
        if fc.co_varnames[0]=='request':
            url_name='%s%s'%(pfx,name)
            if fc.co_argcount==1:
                ul.append(url(r'^%s%s/$'%(url_prefix,name),name,name=url_name))
            elif fc.co_argcount==2:
                if fc.co_varnames[1] in int_names:
                    ul.append(url(r'^%s%s/(?P<%s>\d+)/$'%(url_prefix,name,fc.co_varnames[1]), name,name=url_name) )
                elif fc.co_varnames[1] in slug_names:
                    ul.append(url(r'^%s%s/(?P<%s>[\w-]+)/?$'%(url_prefix,name,fc.co_varnames[1]), name,name=url_name) )
    up=[]
    for p in ul+list(args): up.extend(patterns(view_path,p))
    return up

More like this

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

Comments

sberlotto (on August 5, 2009):

So good... nice job !

#

artur_mwaigaryan (on October 29, 2011):

was feeling like banging my head abt urls....this one is beautiful:-)

#

Please login first before commenting.