获取匹配的URL模式的名称

时间:2022-09-13 00:19:04

I am writing a Django context processor which needs to access the name of the URL pattern that the request got successfully resolved against. Given the pattern,

我正在编写一个Django上下文处理器,它需要访问成功解析请求的URL模式的名称。鉴于模式,

url(r'^home/$', 'app.index', name='website.home')

and the request path /home, I want to get the value for name, which in this case is website.home.

和请求路径/ home,我想得到name的值,在这种情况下是website.home。

I got this code from djangosnippets.org:

我从djangosnippets.org获得了这段代码:

def _get_named_patterns():
    """ Returns a list of (pattern-name, pattern) tuples.
    """
    resolver = urlresolvers.get_resolver(None)
    patterns = sorted(
        (key, val[0][0][0]) for key, val in resolver.reverse_dict.iteritems() if isinstance(key, basestring))
    return patterns

I can use this to achieve my objective but my gut feeling says that there has to be a better method. Thanks for the help.

我可以用它来实现我的目标,但我的直觉是说必须有一个更好的方法。谢谢您的帮助。

1 个解决方案

#1


What about doing it via the request object and a middleware? Like:

那么通过请求对象和中间件来做呢?喜欢:

class MyMiddleware (object):
  def process_view (self, request, view_func, view_args, view_kwargs):
    if view_kwargs.get ('name', None):
      request.name = view_kwargs.get ('name', None)
    ret None

and using the default context preprocessor in settings.py:

并使用settings.py中的默认上下文预处理器:

"django.core.context_processors.request",

Then you can get the name via request.name everywhere after the middleware is executed.

然后,您可以在执行中间件后随处通过request.name获取名称。

Cheers,

#1


What about doing it via the request object and a middleware? Like:

那么通过请求对象和中间件来做呢?喜欢:

class MyMiddleware (object):
  def process_view (self, request, view_func, view_args, view_kwargs):
    if view_kwargs.get ('name', None):
      request.name = view_kwargs.get ('name', None)
    ret None

and using the default context preprocessor in settings.py:

并使用settings.py中的默认上下文预处理器:

"django.core.context_processors.request",

Then you can get the name via request.name everywhere after the middleware is executed.

然后,您可以在执行中间件后随处通过request.name获取名称。

Cheers,