我想知道您在处理此问题时提出了哪些策略。我是 python/django 框架的新手,希望将 View 服务与 ajax 请求 (xhr) 处理分开。
我正在考虑有一个单独的文件 xhrHandler.py 并将特定的 POST/GET 请求路由到/xhr/methodname,然后委托(delegate) views.py 方法返回 View ,并通过 httprequest 进行 View 处理。
想法?
最佳答案
检查 request.is_ajax()
并在需要的地方委托(delegate)。样本处理器:
def view_something(request):
if request.is_ajax():
# ajax
else
# not
您现在可以为这两种情况调用不同的函数(在不同的文件中)。
如果你想更花哨一点,可以为处理程序使用一个装饰器,它会在别处分派(dispatch) Ajaxy 请求:
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"
还有一些模拟测试来锻炼它:
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))
产生:
score ajax handler
score handler
关于Python 将 Ajax 请求与普通页面 View 分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4211883/