【问题标题】:what is the proper way to send and receive json requests in django在 django 中发送和接收 json 请求的正确方法是什么
【发布时间】:2016-05-21 03:15:25
【问题描述】:

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

方法1:使用原始格式:

#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:使用原始格式:

# 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)

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

  • 我采用哪种方法重要吗?
  • 如果是,哪种方法合适?为什么?
  • 如果最好使用原始 json,那么它为什么会抱怨 ajax 请求下方(见下方错误)?

【问题讨论】:

    标签: json django


    【解决方案1】:

    这个问题在django ajax docs解决:

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

    请注意,django-rest-framework 等流行的解决方案正在使用标头方法:

    $.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 docs 建议方法:

    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);
            }
        }
    });
    

    【讨论】:

    • 实际上我的主要问题是是否以原始形式发送 json 数据,从而使用 request.body 检索它。另外,关于您的回答,我不明白如何将 $.ajaxSetup 与 $.ajax 一起使用。这是否甚至需要,因为我注意到 ajax 文档说默认情况下 crossDomain 设置为 false?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多