📜 ⬆️ ⬇️

As in python, externally check the values ​​passed to the function.

A small HowTo for beginners python- programmers about how to externally check some of the values ​​passed to the function. In fact, I needed it in Django , but there’s nothing specific to the framework and ...

UPD Lyrical digression: Initially here I wrote a lot of nonsense because of my crooked understanding of the work of decorators. Now the decision is much more correct and direct. Moreover, I can even clearly explain it, for which many thanks to the commentators.

To begin, I recommend to get acquainted with the work of decorators (very carefully!).

The problem I have literally the following:
')
There is some kind of function for Django before performing which you need to check whether there are some variables in the user profile.

The specific solution is:

def check_nickname(funct): def wrapper(request, *args, **kwargs): if request.user.profile.nickname: return funct(request, *args, **kwargs) else: from django.shortcuts import render_to_response from django.template import RequestContext return render_to_response('need_profile.html', RequestContext(request)) return wrapper 

The check_nickname function is a decorator for a function of the Django type, about which we know for sure that the request parameter of a certain type is passed to it. The decorated function is passed to the wrapper which is returned instead of the decorated function.

The principle of the decorator:

 @f1 def func(x): pass # : def func(x): pass func = f1(func) 


Those. in fact, instead of the original function, the wrapper function returned by the check_nickname decorator is check_nickname . And it is the wrapper receives all the parameters intended for the original function of the view, and on their basis the logic of the following actions is already built.

Thanks again to Deepwalker for the clarification.

Source: https://habr.com/ru/post/134787/


All Articles