Django URL模板匹配(除模式外的所有内容)

Jay*_*012 5 django

我需要一个django正则表达式,它实际上适用于url路由器执行以下操作:

匹配路线中不包含"/ api"的所有内容.

以下不起作用,因为django无法反转(?!

r'^(?!api)
Run Code Online (Sandbox Code Playgroud)

Nic*_*tot 7

通常的方法是订购路线声明,以便全部路线被路线遮蔽/api,即:

urlpatterns = patterns('', 
    url(r'^api/', include('api.urls')),
    url(r'^other/', 'views.other', name='other'),
    url(r'^.*$', 'views.catchall', name='catch-all'), 
)
Run Code Online (Sandbox Code Playgroud)

或者,如果由于某种原因你真的需要跳过一些路由但不能用Django支持的一组正则表达式来做,你可以定义一个自定义模式匹配器类:

from django.core.urlresolvers import RegexURLPattern 

class NoAPIPattern(RegexURLPattern):
    def resolve(self, path):
        if not path.startswith('api'):
            return super(NoAPIPattern, self).resolve(path)

urlpatterns = patterns('',
    url(r'^other/', 'views.other', name='other'),
    NoAPIPattern(r'^.*$', 'views.catchall', name='catch-all'),
)
Run Code Online (Sandbox Code Playgroud)


Aar*_*ier 0

像这样使用消极的目光:

r'^(?!/api).*$'
Run Code Online (Sandbox Code Playgroud)

此链接解释了如何执行此操作:

http://www.codinghorror.com/blog/2005/10/exclusion-matches-with-regular-expressions.html

  • OP 表示这不起作用。[normalize](https://github.com/django/django/blob/1.6/django/utils/regex_helper.py#L46) 的文档字符串确实声明:(6) 对所有其他非捕获( ?...) 形式(例如,向前查找和向后查找匹配)和任何析取('|')结构。 (2认同)