7
我需要以線程安全的方式基於會話中的數據動態生成urlpatterns。Django,動態urlconfs,線程安全
我通過一個自定義的URLResolver實現了這個功能,該功能延遲了網址解析的時間。我確實知道從中間件設置request.urlconf;但有些原因我不能這麼做(Django緩存解析器,在我的情況下會導致無限的內存使用)。
我需要有人來看看實現,看看我是否正確處理線程安全。
謝謝!
的代碼:
的myapp/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()]
富/ 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
你爲什麼需要穿線? –