在Django中发送和接收json请求的正确方法是什么 [英] what is the proper way to send and receive json requests in django

查看:647
本文介绍了在Django中发送和接收json请求的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于此主题的信息很多,但是我仍然不清楚在Django中发送和接收json数据的正确方法是什么.是否使用原始格式.

There are lots of information regarding this topic, but it is still unclear to me what is the correct approach to send and receive json data in django. Whether to use the raw format or not.

方法1:,使用原始格式:

Approach1: NOT using the raw format:

#client
        $.ajax({
            type: "POST",
            url: "api",
            contentType: "application/json; charset=utf-8",
            data: {
                csrfmiddlewaretoken: '{{ csrf_token }}',
                x: $("#x").val(),
            },
            success: response,
            dataType: 'json',
            minLength: 0,
        });

# server - views.py:
@api_view(['GET', 'POST'])
@authentication_classes((TokenAuthentication, SessionAuthentication))
@permission_classes((IsAuthenticated,))
@staff_member_required
def api(request):
    params = request.POST

方法2:使用原始格式:

Approach2: using the raw format:

# client
            $.ajax({
                type: "POST",
                url: "api",
                contentType: "application/json; charset=utf-8",
                headers: {'X-CSRFToken': '{{ csrf_token }}'},
                data: JSON.stringify({
                    x: $("#x").val(),
                }),
                success: response,
                dataType: 'json',
                minLength: 0,
            });

# server - views.py:
@api_view(['GET', 'POST'])
@authentication_classes((TokenAuthentication, SessionAuthentication))
@permission_classes((IsAuthenticated,))
@staff_member_required
def api(request):
    params = json.loads(request.data)

我认为使用原始格式时,您可以传入列表,但如果没有原始格式,则无法理解数据中的列表. 另一方面,approach2需要JSON.stringify和json.dumps. 另外,我不知道为什么approach2会抛出异常,并且您无法访问正文... 我想知道的是:

I think that when using the raw format, you can pass in lists but without the raw format it does not understand lists in your data. On the other hand, approach2 requires JSON.stringify and json.dumps. Also, I do not know why approach2 throws and exception that You cannot access body... What I want to know is:

  • 我采用哪种方法有关系吗?
  • 如果是,哪种方法合适,为什么?
  • 如果最好使用原始json,那么为什么用ajax抱怨 下面的请求(请参见下面的错误)?
  • Does it matter which approach I take?
  • If so which approach is proper and why?
  • If raw json if preferable, then why does it complain with the ajax request below (see error below)?

推荐答案

此问题已在 django ajax文档:

将自定义X-CSRFToken标头设置为CSRF令牌的值. 这通常更容易,因为许多JavaScript框架都提供了允许在每个请求上设置标头的钩子.

set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many JavaScript frameworks provide hooks that allow headers to be set on every request.

注意一些流行的解决方案,例如

Notice than popular solutions like django-rest-framework is using header approach:

$.ajaxSetup({
  beforeSend: function(xhr, settings) {
    if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
      // Send the token to same-origin, relative URLs only.
      // Send the token only if the method warrants CSRF protection
      // Using the CSRFToken value acquired earlier
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});

django文档建议方法:

django docs suggestion approach:

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

这篇关于在Django中发送和接收json请求的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆