我需要以线程安全的方式根据会话中的数据动态生成 urlpatterns。
我通过一个自定义 URLResolver 实现了这一点,该 URLResolver 将 url 解析推迟到以后。我确实知道从中间件设置 request.urlconf ;但是我不能这样做是有原因的(Django缓存解析器,在我的情况下会导致无限的内存使用)。
我需要有人来看看实现,看看我是否正确处理了线程安全。
谢谢!
编码:
我的应用程序/urls.py:
urlpatterns = patterns('',
# other urlconfs
url(r'^/foo', include('foo.urls')),
)
富/urls.py:
import threading
from django.core.urlresolvers import ResolverMatch
class MyResolver(RegexURLResolver):
def __init__(self):
self.resolver = threading.local()
return super(MyResolver, self).__init__(r'', None)
@property
def urlconf_module(self):
return self.resolver.value
def resolve(self, path):
def view(request):
resolver = request.session.get('myresolver', 'default')
resolver = getattr(import_module('foo.resolvers'), resolver)
self.resolver.value = resolver()
view, args, kwags = super(MyResolver, self).resolve(path)
return view(request, *args, **kwargs)
return ResolverMatch(view, (), {})
urlpatterns = [MyResolver()]
foo/resolvers.py:
class default(object):
@property
def urlpatterns(self):
return patterns('foo.views',
url(r'', 'error'),
)
class test(object):
@property
def urlpatterns(self):
return dynamically_generated_urlpatterns