title: Django, dynamic urlconfs, thread-safety
body: <p>I need to dynamically generate urlpatterns based on data in the session in a thread-safe way.</p>
  
  <p>I implemented this via a custom URLResolver that defers url resolving until later.  I do know about setting request.urlconf from a middleware; but there are reasons I cannot do that (Django caches resolvers, and in my case would result in unbounded memory usage).</p>
  
  <p>I need someone to take a look at the implementation and see if I've handled the thread-safety correctly.</p>
  
  <p>Thanks!</p>
  
  <p>The code:</p>
  
  <p>myapp/urls.py:</p>
  
  <pre><code>urlpatterns = patterns('',
      # other urlconfs
      url(r'^/foo', include('foo.urls')),
  )
  </code></pre>
  
  <p>foo/urls.py:</p>
  
  <pre><code>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()]
  </code></pre>
  
  <p>foo/resolvers.py:</p>
  
  <pre><code>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
  </code></pre>