Sobes.tech
Junior — Middle

Can you explain how request routing works in Django and how it maps URLs to handlers?

sobes.tech AI

Answer from AI

In Django, request routing is handled through the URL configuration system (urls.py). When an HTTP request comes in, Django sequentially checks the request URL against a list of patterns defined in the urls.py files, starting from the root.

Each pattern is a rule that matches a part of the URL with a specific handler (view function or class). If the URL matches the pattern, the corresponding handler is called, which generates a response.

Example of a simple route:

from django.urls import path
from . import views

urlpatterns = [
    path('articles/<int:year>/', views.year_archive),
]

Here, if the URL matches the pattern 'articles/2023/', the parameter year will be 2023, and the function year_archive(request, year=2023) will be called.

Thus, the routing mechanism is a sequential check of URL patterns and calling the associated handler upon a match.