django url解析中的ResolverMatch

了解这个问题,源于昨天开发时遇到的一个小小的问题。

问题描述如下:

比如,我有一个url,定义如下:

path('res_edit/<app>/<env>/', AppResEditView.as_view(), name='res_edit'),

那如果我现在拿到一个url是如下:

/res_edit/App_70/UAT/

那么,问题来了:

我如何通过django原生的途径,拿到app=App_70, env=UAT这样的变量?

============================================================

找了一些文档,最后,发现官网的还是最有效:

https://docs.djangoproject.com/en/2.1/ref/urlresolvers/

原来,resolve函数就可以返回一个三元组,而其中的字典,即我们需要的东东。如下:

func, args, kwargs = resolve(self.request.path)
app = kwargs['app']
env = kwargs['env']

官方说明如下:

resolve( pathurlconf=None) [source]

path is the URL path you want to resolve. As with reverse(), you don’t need to worry about the urlconf parameter. The function returns a ResolverMatchobject that allows you to access various metadata about the resolved URL.

If the URL does not resolve, the function raises a Resolver404 exception (a subclass of Http404) .

猜你喜欢

转载自www.cnblogs.com/aguncn/p/10340522.html