Python separating Ajax requests from normal page views
I'm wondering what are some strategies that you've come up wh开发者_如何学运维en dealing with this. I'm new to the python/django framework and would like to separate the serving of view from the handling of ajax requests (xhr).
I'm thinking of having a separate file xhrHandler.py and route specific POST/GET requests to /xhr/methodname and then delegate the views.py methods to return the view passing along the httprequest for view processing.
Thoughts?
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
精彩评论