Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically add URL Patterns in Django?

Is there a way to programmatically add URL Patterns to Django without having to restart the server?

Or is there a way force Django to reprocess/cache URL patterns ( the URLconf )?

like image 975
Tom Neyland Avatar asked Feb 01 '11 18:02

Tom Neyland


People also ask

How does Django define URL pattern?

To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a mapping between URL path expressions to Python functions (your views). This mapping can be as short or as long as needed. It can reference other mappings.

How do I create a URL in Django?

Creating a Django URL Through URL() The template folder has to be created under the primary project folder. 2. Tag the Template folder in settings.py file: The settings.py file needs to have the tag for the templates folder so that all templates are accessible for the entire Django project.


2 Answers

If you use gunicorn without code preloading, just send a HUP to the gunicorn master process, it will spawn new workers which load the new code, and gracefully shut down the old ones, without a single lost request!

like image 97
rewritten Avatar answered Oct 21 '22 14:10

rewritten


I tried something like this by hacking some things in django.core.urlresolvers – it worked for me but note that it's a hack. I don't still have the code, but I did something like this:

  1. Django typically uses urlresolvers.get_resolver() to get a RegexURLResolver which is responsible for resolving URLs. Passing None to this function gets your "root" URLConf.
  2. get_resolver() uses a cache, _resolver_cache, for loaded URLConfs.
  3. Resetting _resolver_cache should force Django to recreate a clean URLResolver.

Alternatively, you might try to unset the _urlconf_module attribute of the root RegexURLResolver, which should force Django to reload it (not sure about this though, it's possible that the module will be cached by Python).

from urlresolvers import get_resolver

delattr(get_resolver(None), '_urlconf_module')

Again, not guaranteed that this will work (I'm working from memory from code that I've obviously discarded for some reason). But django/core/urlresolvers.py is definitely the file you'll want to look at.

EDIT: Decided to experiment some with this and it didn't work...

EDIT2:

As I thought, your URL modules will be cached by Python. Simply reloading them as they change might work (using reload). If, your problem is that you're dynamically constructing urlpatterns based on some data which might change.

I tried reloading my root URLs (project.urls) and a suburl module (app.urls). That's all I had to do for the new URLs to be displayed by get_resolver(None).url_patterns

So the trick might be this simple: Manually reload your URL module.

like image 44
vicvicvic Avatar answered Oct 21 '22 14:10

vicvicvic