Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Django - How do view wrappers receive the request, keyword and positional arguments?

In chapter 8 of the Django book there is an example showing a fundamental view wrap method, which receives another view method passed in from any single arbitrary URLconf:

def requires_login(view):
    def new_view(request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseRedirect('/accounts/login/')
        return view(request, *args, **kwargs)
    return new_view

I follow most of the logic here, but what I'm not understanding is how the nested new_view definition is receiving the request, *args and **kwargs as it's not being explicitly passed into the requires_login definition.

How exactly is the new_view definition receiving these arguments?

like image 223
ground5hark Avatar asked Feb 19 '10 07:02

ground5hark


1 Answers

How new_view works

Let's first look at the new_view function:

def new_view(request, *args, **kwargs):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/')
    return view(request, *args, **kwargs)

When new_view is called, it checks whether the user is authenticated. If the user is authenticated, then new_view calls view and passes it all of the arguments (request, positional arguments, and keyword arguments).

Defining new_view

new_view is not automatically executed. We are using def to define the function, but we are not executing it right away. Instead, we return new_view as a function. Imagine the following code:

def my_view(request):
    # ... some view stuff happens here

my_new_view = requires_login(my_view)

Now, my_new_view is a function. I can call it just like any other function. At no point so far has this new function actually been called.

When my_new_view is called, it receives all its arguments. It then calls my_view, passing all the arguments (request, positional arguments, and keyword arguments) to my_view instead.

(All of this assumes that the user is authenticated, of course. Otherwise, when you call my_new_view, you would get an HttpResponseRedirect, and my_view would never be called.)

view as an argument

requires_login receives a function called view as its argument. view refers to a function, but we're not executing that function yet. view is executed only when new_view is executed.

like image 120
Wesley Avatar answered Oct 05 '22 23:10

Wesley