Reputation: 49
I have huge urls.py
with dozen of lines like:
url(r'^do_foo$', views.do_foo),
i.e. url exactly match name of function within views.
I don't want to create a dispatcher that takes url as parameter and find the appropriate method for performance reason.
Q:
Is there a way to either shorten urls.py
to one line like
url(r'^(.*)$', 'views.\\1'),
or get rid of urls.py
entirely.
Upvotes: 0
Views: 871
Reputation: 37319
The urlpatterns
variable is just Python, so if you can determine which callables you want to map to URLs you can automate it:
import inspect
import views
urlpatterns = [url(r'^%s$' % name, view) for name, view in views.__dict__.items()
if callable(view) and
inspect.getargspec(view)[0][0] == 'request']
But think carefully before doing so - automatically exposing all your views as URLs can open up parts of your app you didn't intend to make public. The inspect argspec check above is a tiny step towards not accidentally opening up too much, but I wouldn't want to rely on it too deeply.
Upvotes: 0
Reputation: 56
The $ sign at the end of each URL stands for an exact match at the end
For example,
url(r'^do_foo$', views.do_foo)
will match only /do_foo whereas
url(r'^do_foo', views.do_foo)
will match
doo_foo/hello
doo_foo/abcd/bar
You can use this to reduce the size of your urls.py
You can't get rid of urls.py entirely, but can map all urls to the same view function using
You can map all urls to the same view function using
url(r'', views.do_foo)
Upvotes: 1