Reputation: 8992
I'm trying to write a custom decorator. I want to check if all the required parameters are sent with the request. I wrote something like this:
def get_parameters_required(parameters=None):
missing_parameter = False
if parameters is not None:
for parameter in parameters:
if request.GET.get(parameter) is None:
missing_parameter = True
if missing_parameter:
return HttpResponse(status=400)
def _get_parameters_required(view_func):
def _decorator(request, *args, **kwargs):
response = view_func(request, *args, **kwargs)
return response
return wraps(view_func)(_decorator)
return _get_parameters_required
This doesn't work because i don't have the request object where i check the parameters. And where i have the request object, i don't have the parameters object.
Is there any built-in solution to this problem or how can i do write this decorator in the correct way?
Upvotes: 0
Views: 229
Reputation: 16733
Why don't you ensure this in Serializer
instead, after all that's what they are meant for?
If you are using function-based DRF views :-
def get_parameters_required(parameters=None):
def _get_parameters_required(view_func):
def _decorator(request, *args, **kwargs):
missing_parameter = False
if parameters is not None:
for parameter in parameters:
if request.GET.get(parameter) is None:
missing_parameter = True
if missing_parameter:
return HttpResponse(status=400)
response = view_func(request, *args, **kwargs)
return response
return wraps(view_func)(_decorator)
return _get_parameters_required
In your current implementation, you need to check for parameter inside request method not outside.
Upvotes: 1
Reputation: 599490
The whole if
statement should be inside the nested _decorator
function, where you do have access to the request. You then only call view_func()
if missing_parameter is False.
That said, as hspandher points out, this should be done by a Serializer.
Upvotes: 1