DEV Community

José Sobral
José Sobral

Posted on

Why Django uses regex on routes?

Configuration and Why

Django is a web framework which allows you to build your whole application using the concept of a project with one or several apps. There are tons of philosophies originated by this approach (like Modular Development, Separation of Concerns, Plug-n-play Features and etc).

All of these apps are configured by your project. One of these configurations is the ROOT_URLCONF in which allows you to pointer the 'master' url file config. This is fundamental to put in practice the django philosophies mentioned.

Importance of regular expressions

When i've first encountered regular expressions in Django apps, i think that was an over engineering process to build routes (as any junior can think). After some experiences i've understand the reason why and i think these two resources compiles well them

  1. Django Book, The definitive guide to Django: Web Development Done Right

A route example from the book:

from django.conf.urls.defaults import *
from mysite.views import current_datetime
urlpatterns = patterns('',
 (r'^time/$', current_datetime),
)
Enter fullscreen mode Exit fullscreen mode

The author explanation

This concept is best explained by example. If we had instead used the pattern '^time/' (without a dollar sign at the end), then any URL that starts with time/ would match, such as /time/foo and /time/bar, not just /time/. Similarly, if we had left off the initial caret character ('time/$'), Django would match any URL that ends with time/, such as /foo/bar/time/. Thus, we use both the caret and dollar sign to ensure that only the URL /time/ matches. Nothing more, nothing less.

  1. One of the Django founders, on Reddit

Image description

In summary, django uses pattern matching to register routes and using regex you can build it in a easy and performatic way.

Open Source Examples

Flagsmith, 2.7k stars

https://github.com/Flagsmith/flagsmith/blob/main/api/api/urls/v1.py

Healthchecks, 6.5k stars

https://github.com/healthchecks/healthchecks

Top comments (0)