Creating custom decorators for your views

We will restrict our AJAX views to allow only requests generated via AJAX. The Django request object provides an is_ajax() method that checks whether the request is being made with XMLHttpRequest, which means it is an AJAX request. This value is set in the HTTP_X_REQUESTED_WITH HTTP header, which is included in AJAX requests by most JavaScript libraries.

We will create a decorator for checking the HTTP_X_REQUESTED_WITH header in our views. A decorator is a function that takes another function and extends the behavior of the latter without explicitly modifying it. If the concept of decorators is foreign to you, you might like to take a look at https://www.python.org/dev/peps/pep-0318/ before you continue reading.

Since our decorator will be generic and could be applied to any view, we will create a common Python package in our project. Create the following directory and files inside the bookmarks project directory:

common/
__init__.py
decorators.py

Edit the decorators.py file and add the following code to it:

from django.http import HttpResponseBadRequest

def ajax_required(f):
def wrap(request, *args, **kwargs):
if not request.is_ajax():
return HttpResponseBadRequest()
return f(request, *args, **kwargs)
wrap.__doc__=f.__doc__
wrap.__name__=f.__name__
return wrap

The preceding code is our custom ajax_required decorator. It defines a wrap function that returns an HttpResponseBadRequest object (HTTP 400 code) if the request is not AJAX. Otherwise, it returns the decorated function.

Now, you can edit the views.py file of the images application and add this decorator to your image_like AJAX view, as follows:

from common.decorators import ajax_required

@ajax_required
@login_required
@require_POST
def image_like(request):
# ...

If you try to access http://127.0.0.1:8000/images/like/ directly with your browser, you will get an HTTP 400 response.

Build custom decorators for your views if you find that you are repeating the same checks in multiple views.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.165.247