所以我尝试了几件事,最后我想出了自己的解决方案。首先,我将 urlpatterns 转换为 JavaScript 可以理解的形式:
import re
converter = re.compile(r"\?P<.*?>")
def recursive_parse(urlpatterns, lst):
for pattern in urlpatterns:
obj = {
"pattern": converter.sub("", pattern.regex.pattern)
}
if hasattr(pattern, "name") and pattern.name is not None:
obj["name"] = pattern.name
if hasattr(pattern, "namespace"):
obj["namespace"] = pattern.namespace
if hasattr(pattern, "url_patterns"):
if "urls" not in obj:
obj["urls"] = []
recursive_parse(pattern.url_patterns, obj["urls"])
lst.append(obj)
def generate_paths(urlpatterns):
paths = []
recursive_parse(urlpatterns, paths)
return paths
然后我调用generate_paths(urlpatterns)
, JSON-stringify 结果并将其传递给 JavaScript(请注意,在 JavaScript 中,我必须将正则表达式作为字符串转换为RegExp
对象)。在 JavaScript 中我有
var recursive_check = function(url, patterns, names, args) {
var l = patterns.length;
for (var i = 0; i < l; i++) {
var pat = patterns[i],
match = pat.pattern.exec(url);
pat.lastIndex = 0;
if (match) {
names.push(pat.namespace || pat.name);
var f = match.shift(),
url = url.replace(f, ""),
ml = match.length;
for (var j = 0; j < ml; j++) {
args.push(match[j]);
}
if (pat.urls) {
recursive_check(url, pat.urls, names, args);
}
break;
}
}
};
var fire_handler = function(url) {
var names = [], args = [];
recursive_check(url, patterns, names, args);
// do something...
};
现在// do something...
我可以用names
and做一些事情了args
。例如,我可以保留一个命名处理程序的字典,我可以搜索一个处理程序(基于names
)并使用args
.
这就是对我有用的解决方案。转换urlpatterns
为 JavaScript 模式可能并不完美(因为converter
似乎有点过于简化了),但它适用于大多数简单的情况。