论坛首页 编程语言技术论坛

Django的url的简化和默认映射

浏览 4639 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-06-09   最后修改:2009-06-09
django的url采用正则表达式进行配置,虽然强大却也广为诟病。反对者们认为django的url配置过于繁琐,且不支持默认的路由功能。
我倒觉得还好,只是如果觉得不爽,为什么不自己小小的hack一下,反正也就几行代码的事。
相关代码和详细的例子请参考附件。
url的默认路由
from url_helper import execute, url_
import views
 
urlpatterns += patterns('',
    url(r'^(?P<urls>.*)', execute, {'views': views}),
)

在urls.py里增加如下配置,其中views为需要进行路由的views模块。url的规则为 /action/param1/param2/…/ 。
例如:
/edit/4/
 
def edit(request, n="id"):
    html = """ edit object: %s""" % n
    return HttpResponse(html)

在没有指定action的时候默认使用的action为index。
提供函数url_简化url配置
仿照ROR的做法,参数用”:”标识。
例如:
url_(r’/space/:username/:tag/’, views.url_), 对应的django
url配置为url(r’^space/(?P[^/]+)/(?P[^/]+)/$’,
views.url_),
url_(r’/space/:username/:tag/’, views.url_), 
/space/vicalloy/just/
 
def url_(request, username, tag):
    html = """ username: %s <br/> tag: %s""" % (username, tag)
    return HttpResponse(html)

完整代码
就如前面说的,代码非常少。不过实际应用的话,应当还需要做一些扩展。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django import http
from django.conf.urls.defaults import url
import re
 
def execute(request, urls, views):
    """
    urls [methodName/]param1/param2/.../
    methodName default index
    """
    def get_method(views, methodName):
        try:
            return getattr(views, methodName)
        except Exception, e:
            return None
    method = None
    params = [e for e in urls.split("/") if e]
    params.reverse()
    if params:
        method = get_method(views, params.pop())
    if not method:
        method = get_method(views, 'index')
    if not method:
        raise http.Http404('The requested admin page does not exist.')
    return method(request, *params)
 
def url_(*args,**dic):
    regex = args[0]
    if regex[0] == "/":
        regex = regex[1:]
    regex = '^' + regex
    regex = regex + '$'
    regex = re.sub(":[^/]+",
            lambda matchobj: "(?P<%s>[^/]+)" % matchobj.group(0)[1:],
            regex)
    return url(regex, *args[1:], **dic)


   发表时间:2009-10-14  
# ======= /urls.py ==============

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^someurl/',include('someapp.url_view')), 
)

# ======= /someapp/url_view.py ==

from django.http import HttpResponse
from tourl import tourl


@tourl(r'^and/$')
def and_(request):
    return HttpResponse('and')

@tourl(r'^gg/$')
def index(request):
    return HttpResponse('OK')

# ======= /someapp/tourl.py ==

from django.conf.urls.defaults import *
import sys
import functools
def tourl(url_patern,*args,**kwargs):
    def paramed_decorator(func):
        @functools.wraps(func)
        def decorated(self):
            return func(self)
        module =sys.modules[func.__module__]
        
        if not hasattr(module, 'urlpatterns'):
            module.urlpatterns = patterns('',)
              
        module.urlpatterns   += patterns('',
            url(url_patern,decorated,*args,**kwargs), 
        )
        return decorated 
    return paramed_decorator

0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics