开发者

Django url.py without method names

开发者 https://www.devze.com 2023-01-05 01:08 出处:网络
In my Django project, my url.py module looks something like this: urlpatterns = patterns(\'\', (r\'^$\', \'web.views.home.index\'),

In my Django project, my url.py module looks something like this:

urlpatterns = patterns('',
    (r'^$', 'web.views.home.index'),
    (r'^home/index', 'web.views.home.index'),
    (r'^home/login', 'web.views.home.login'),
    (r'^home/logout', 'web.views.home.logout'),
    (r'^home/register', 'web.views.home.register'),
)

Is t开发者_如何学Pythonhere a way to simplify this so that I don't need an entry for every method in my view? Something like this would be nice:

urlpatterns = patterns('',
    (r'^$', 'web.views.home.index'),
    (r'^home/(?<method_name>.*)', 'web.views.home.(?P=method_name)'),
)

UPDATE

Now that I know at least one way to do this, is this sort of thing recommended? Or is there a good reason to explicitly create a mapping for each individual method?


You could use a class-based view with a dispatcher method:

class MyView(object):
    def __call__(self, method_name):
        if hasattr(self, method_name):
            return getattr(self, method_name)()


    def index(self):
        ...etc...

and your urls.py would look like this:

from web.views import MyView
urlpatterns = patterns('',
    (r'^$', 'web.views.home.index'),
    (r'^home/(?<method_name>.*)', MyView()),
)


May be something like that:

import web.views.home as views_list
urlpatterns = patterns('',
    (r'^$', 'web.views.home.index'),
    *[(r'^home/%s' % i, 'web.views.home.%s' % i) for i in dir(views_list)]
)
0

精彩评论

暂无评论...
验证码 换一张
取 消