1

我们可以在 django 中使用 express.js 之类的 url 配置吗?有时使用正则表达式会很痛苦!

express.js 网址:

app.get('/users/:id/feed',function(){})

django 网址:

url(r'^users/(?P<id>.*)/feed$', 'users.views.feed')

我认为 express 的 url conf 比 django 的简单。像这样在 django 中使用 url 会很好,看起来不错:

url('/users/:id/feed', 'users.views.feed')
4

2 回答 2

2

在核心 Django 中,您只能使用正则表达式指定 url。

我不熟悉 express.js 但是通过使用正则表达式,你可以做一些很酷的事情,比如:

  • 位置参数和命名参数

    # named
    url(r'^(?P<foo>.*)/(?P<foo2>.*)/$', 'view', name='view')
    
    # corresponds to
    # something does not have to be supplied
    def view(request, something=None, foo=None, foo2=None)
        ...
    

    # positional
    url(r'^(.*)/(.*)/$', 'view', name='view')
    
    # corresponds to
    # all groups in regex are supplied in the same order (positions)
    def view(request, foo, foo2)
        ...
    
  • 计算反向网址

    # with
    url(r'^some/path/(?P<foo>.*)/(?P<foo2>.*)/$', 'view', name='view')
    
    >>> reverse('view', kwargs={'foo':'hello', 'foo2':'world'})
    u'some/path/hello/world/'
    
  • 限制网址

    url(r'^some/path/(?P<id>\d+)/$', 'view', name='view')
    # will only allow urls like
    # some/path/5/
    # some/path/10/
    
    # and will reject
    # some/path/hello/
    # some/path/world/
    
于 2012-11-19T02:45:23.457 回答
2

为了在 Django 中使用更简单的 url 结构,您需要编写一个实用函数,将您的 url 格式转换为正则表达式格式。

这是基于您的示例的简单函数:

def easy_url(url_str):
    patt = re.compile(r':\w+/?')
    matches = patt.findall(url_str)
    for match in matches:
        var = match[1:-1]
        # generate re equivalent 
        var_re = r'(?P<%s>\w+)/'%var
        url_str = url_str.replace(match, var_re) 
    url_str += '$'
    return url_str

# in your url file
url(easy_url('/users/:id/feed/'), 'users.views.feed')

您可以更新此函数以指定 url 变量的类型,例如仅数字等。

然而,正则表达式非常强大,你可以用它们做很多事情。因此,您应该仅将此类包装器用于具有简单规则的 url,以使其轻量级。

于 2012-11-19T11:27:28.553 回答