[Django]-Python separating Ajax requests from normal page views

3👍

Check request.is_ajax() and delegate wherever you need. Sample handler:

def view_something(request):
    if request.is_ajax():
       # ajax
    else
       # not

You can now call different functions (in different files) for the two cases.

If you want to be fancier, use a decorator for the handler that will dispatch ajaxy requests elsewhere:

def reroute_ajaxy(ajax_handler):
    def wrap(f):
        def decorate(*args, **kwargs):
            if args[0].is_ajax():
                return ajax_handler(args)
            else:
                return f(*args, **kwargs)
        return decorate
    return wrap

def score_ajax_handler(request):
    print "score ajax handler"


@reroute_ajaxy(score_ajax_handler)
def score_handler(request):
    print "score handler"

And some mock testing to exercise it:

class ReqMock:
    def __init__(self, ajax=False):
        self.ajax = ajax
    def is_ajax(self):
        return self.ajax


score_handler(ReqMock(True))
score_handler(ReqMock(False))

Produces:

score ajax handler
score handler

Leave a comment