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 )?
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.
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.
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!
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:
urlresolvers.get_resolver()
to get a RegexURLResolver
which is responsible for resolving URLs. Passing None
to this function gets your "root" URLConf.get_resolver()
uses a cache, _resolver_cache
, for loaded URLConfs._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 reload
ing 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With