Nicer URL mappings in Django
Posted 2013-05-11 17:15. Last updated 2018-01-05 14:00. Tagged django, python, web.
URL mappings in django consists more or less of a list of (regex, handler) tuples, if the regular expression matches the requested URL, the handler is used to serve the request. The regular expressions themselfes tends to be rather long and not as readable as I would want them to. Let’s see if we can fix that.
Update 2018-01-05 14:00: Django 2.0 was recently released and supports a scheme simliar to what I present here (but more generic). If you use this, consider upgrading to Django 2.0 and see the documentation on the URL dispatcher.
Here’s a few lines of
urls.py from the main app of my blog server,
as an example:
, , , ,
As you see, the regular expressions is rather repetitive.
(?P<name>[a-z0-9-]+) comes up a lot.
Since we know we are talking about URLs, we should be able to improve
How about we assume by default that parameters should match the format
[a-z0-9-]+, and note beforehand when parameters should look like
How about like this:
, , , , ,
Admittedly, this is one lines more but it is a few characters shorter, and more important, I think it is much easier to read. Luckily, this is Python, so it is quite easy to make the second version work. Here’s one way of doing it:
= = r = = return r % return =