0

While testing django cashing on our development server, one of our senior asked if is it possible to change the value of caching timeout on urls.py without restarting the http service.

On first note, I was 100% sure it can be done by changing the timeout value dynamically.

For example - As suggested by my other colleague, If we save the timeout value in separate xml file and read this file value in urls.py and assign that value on the caching command, then by changing the value in the xml file, caching timeout will be updated without restarting the http service.

But when we tested this, we came to an understanding that it works only on first hit as the urlpattern object is passed to django server and urls.py never runs again unless the http service is restarted.

In the end to get our requirement done, we had to write few more script inside the view function to load the urls.py again so that it reads the new caching timeout value.

So my question is why this urls.py is not loaded every time on every url hit but only once on first time?, where does this urlpattern object goes?, Any Idea!

  • Probably because there's a reasonable expectation that urls.py does not get modified on a regular basis. If this file is being changed often, I'd re-examine your development strategy. – Robert Harvey Apr 16 '15 at 16:54
  • I know that urls.py is does not get modified on a regular basis and that's why Django Team has made it load only once. My question is where this urlpattern object is passed and which function or class is responsible for this. I want to understand the object flow structure. – Avinash Kr Mallik Apr 16 '15 at 17:24
2

It's not passed anywhere, but it is imported only once. Python runs a module when it is imported, and after that it is just kept in memory. Django can access the urlpatterns variable in the module whenever it once, the module isn't re-run.

That's not specific to Django or urls.py, it's just how Python modules work.

  • Or as commonly known: Singleton pattern – Onilol Apr 9 '18 at 14:49
1

Looking through the documentation, I found this after searching the Django repository for re.compile. Look through django.core.urlresolvers. RegexURLResolver is called on the root urlconf unless it's set by whatever calls get_resolver. The output of get_resolver, and therefore the result of building the URL resolver, is cached:

@lru_cache.lru_cache(maxsize=None)
def get_resolver(urlconf):
if urlconf is None:
    from django.conf import settings
    urlconf = settings.ROOT_URLCONF
return RegexURLResolver(r'^/', urlconf)

re.compile is called twice in the RegexURLResolver class. You may want to look further into that, and the @lru_cache decorator, for whatever it is you want to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.