The callback function object in Django URLconf is

2019-08-19 14:08发布

问题:

I am learing Django on Django at a glance | Django documentation | Django

When introducing URLconf It reads:

To design URLs for an app, you create a Python module called a URLconf. A table of contents for your app, it contains a simple mapping between URL patterns and Python callback functions.

Nevertheless, a callback function is not called.

mysite/news/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^articles/([0-9]{4})/$', views.year_archive),
]
print('callback funtion:',views.year_archive)

output:

callback function: <function views.year_archive at 0x1039611e0>

So it a funtion object which is not called.

I suppose it should be views.year_archive() to enable it to call.

If not called,how does it work? I assume there a decorator to process it in parent class.

I check the source codes of urldjango.conf.urls | Django documentation | Django

The key statement is:

 elif callable(view):
        return RegexURLPattern(regex, view, kwargs, name)

I dig on to explore LocaleRegexProvider, RegexURLPattern django.urls.resolvers | Django documentation | Django. No appopriate codes were found to call the callback function views.year_archive

What's the mechanism of its working?

回答1:

Django automatically calls the callback view function whenever a request is made to the given url pattern.

To understand how it works, look at this example:

>>> def a():
        print("Called function a")

>>> def b():
        print("Called function b")

>>> def c(callback):
        # call the callback function like this
        callback()

>>> c(a)
Called function a
>>> c(b)
Called function b

Basically, this is how Django's url function works.