Python 将 Ajax 请求与普通页面 View 分开

标签 python ajax django design-patterns xmlhttprequest

我想知道您在处理此问题时提出了哪些策略。我是 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/

相关文章:

django - CMS+博客+电子商务 : django or web2py

python - 获取列具有条件的 Pandas 数据框的指定索引

python - 将 <Python.h> 包含到 makefile.am

php - iframe 的 SEO 友好替代方案?

ajax - 用户界面 :repeat value expression evaluated on every ajax request

django - 在 Django Rest Framework 中生成身份验证 token 时出错

python - django.db.utils.IntegrityError : (1062, "Duplicate entry ' ' 对于键 'slug' ")

python - 如何使用Paramiko exec_command获取每个依赖的命令执行输出

javascript - 从js脚本发送数据到当前的php文件

django - 按日期时间的月/日订购 Django QuerySet?