Django URL模板匹配(除模式外的所有内容) [英] Django URL template match (everything except pattern)

查看:57
本文介绍了Django URL模板匹配(除模式外的所有内容)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个Django regex,它实际上将对url路由器起作用,以执行以下操作:

I need a django regex that will actually work for the url router to do the following:

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

Match everything that does not contain "/api" in the route.

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

The following does not work because django can't reverse (?!

r'^(?!api)

推荐答案

通常的解决方法是对路由声明进行排序,以使/api 路线,即:

The usual way to go about this would be to order the route declarations so that the catch-all route is shadowed by the /api route, i.e.:

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

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

Alternatively, if for some reason you really need to skip some routes but cannot do it with the set of regexes supported by Django, you could define a custom pattern matcher class:

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'),
)

这篇关于Django URL模板匹配(除模式外的所有内容)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆