복붙노트

[PYTHON] 내 장고 요청에서 내 JSON 데이터는 어디에 있습니까?

PYTHON

내 장고 요청에서 내 JSON 데이터는 어디에 있습니까?

Django / Python으로 들어오는 JSON / Ajax 요청을 처리하려고합니다.

request.is_ajax ()는 요청에서 True이지만 페이로드가 JSON 데이터와 어디에 있는지 알 수 없습니다.

request.POST.dir이 포함되어 있습니다 :

['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
 '__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding', 
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding', 
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update', 
'urlencode', 'values']

분명히 요청 포스트 키에는 키가 없습니다.

Firebug에서 POST를 살펴보면 요청시 JSON 데이터가 전송됩니다.

해결법

  1. ==============================

    1.JSON을 Django에 게시하는 경우 request.body (Django의 request.raw_post_data <1.4)를 원한다고 생각합니다. 이렇게하면 게시물을 통해 전송 된 원시 JSON 데이터가 제공됩니다. 거기에서 당신은 그것을 더 처리 할 수 ​​있습니다.

    JSON을 Django에 게시하는 경우 request.body (Django의 request.raw_post_data <1.4)를 원한다고 생각합니다. 이렇게하면 게시물을 통해 전송 된 원시 JSON 데이터가 제공됩니다. 거기에서 당신은 그것을 더 처리 할 수 ​​있습니다.

    다음은 JavaScript, jQuery, jquery-json 및 Django를 사용하는 예제입니다.

    자바 스크립트 :

    var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
                   allDay: calEvent.allDay };
    $.ajax({
        url: '/event/save-json/',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: $.toJSON(myEvent),
        dataType: 'text',
        success: function(result) {
            alert(result.Result);
        }
    });
    

    장고 :

    def save_events_json(request):
        if request.is_ajax():
            if request.method == 'POST':
                print 'Raw Data: "%s"' % request.body   
        return HttpResponse("OK")
    

    장고 <1.4 :

      def save_events_json(request):
        if request.is_ajax():
            if request.method == 'POST':
                print 'Raw Data: "%s"' % request.raw_post_data
        return HttpResponse("OK")
    
  2. ==============================

    2.나는 똑같은 문제가 있었다. 복잡한 JSON 응답을 게시했는데 request.POST 사전을 사용하여 데이터를 읽을 수 없습니다.

    나는 똑같은 문제가 있었다. 복잡한 JSON 응답을 게시했는데 request.POST 사전을 사용하여 데이터를 읽을 수 없습니다.

    내 JSON POST 데이터 :

    //JavaScript code:
    //Requires json2.js and jQuery.
    var response = {data:[{"a":1, "b":2},{"a":2, "b":2}]}
    json_response = JSON.stringify(response); // proper serialization method, read 
                                              // http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
    $.post('url',json_response);
    

    이 경우 aurealus에서 제공하는 방법을 사용해야합니다. request.body을 읽고 json stdlib로 deserialize하십시오.

    #Django code:
    import json
    def save_data(request):
      if request.method == 'POST':
        json_data = json.loads(request.body) # request.raw_post_data w/ Django < 1.4
        try:
          data = json_data['data']
        except KeyError:
          HttpResponseServerError("Malformed data!")
        HttpResponse("Got json data")
    
  3. ==============================

    3.방법 1

    방법 1

    클라이언트 : JSON으로 보내기

    $.ajax({
        url: 'example.com/ajax/',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        processData: false,
        data: JSON.stringify({'name':'John', 'age': 42}),
        ...
    });
    
    //Sent as a JSON object {'name':'John', 'age': 42}
    

    서버 :

    data = json.loads(request.body) # {'name':'John', 'age': 42}
    

    방법 2

    클라이언트 : x-www-form-urlencoded로 보내기 (참고 : contentType 및 processData가 변경되었으므로 JSON.stringify는 필요하지 않습니다.)

    $.ajax({
        url: 'example.com/ajax/',
        type: 'POST',    
        data: {'name':'John', 'age': 42},
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',  //Default
        processData: true,       
    });
    
    //Sent as a query string name=John&age=42
    

    서버 :

    data = request.POST # will be <QueryDict: {u'name':u'John', u'age': 42}>
    

    1.5 이상에서 변경됨 : https://docs.djangoproject.com/en/dev/releases/1.5/#non-form-data-in-http-requests

    아마 관련이있다.

  4. ==============================

    4.request.raw_response는 이제 더 이상 사용되지 않습니다. request.body를 사용하여 XML 페이로드, 바이너리 이미지 등과 같은 비 전통적인 양식 데이터를 처리하십시오.

    request.raw_response는 이제 더 이상 사용되지 않습니다. request.body를 사용하여 XML 페이로드, 바이너리 이미지 등과 같은 비 전통적인 양식 데이터를 처리하십시오.

    문제에 대한 장고 문서화.

  5. ==============================

    5.파이썬 3을 기억하는 것이 중요하다. 문자열을 표현하는 다른 방법이있다. 그것들은 바이트 배열이다.

    파이썬 3을 기억하는 것이 중요하다. 문자열을 표현하는 다른 방법이있다. 그것들은 바이트 배열이다.

    Django 1.9와 Python 2.7을 사용하여 JSON 데이터를 헤더 (header가 아닌)에 전송하면 다음과 같은 것을 사용할 수 있습니다 :

    mydata = json.loads(request.body)
    

    그러나 Django 1.9와 Python 3.4에서는 다음을 사용합니다 :

    mydata = json.loads(request.body.decode("utf-8"))
    

    방금 Py3 Django 앱을 만들면서이 학습 곡선을 훑어 보았습니다!

  6. ==============================

    6.장고 1.6 파이썬 3.3

    장고 1.6 파이썬 3.3

    고객

    $.ajax({
        url: '/urll/',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(json_object),
        dataType: 'json',
        success: function(result) {
            alert(result.Result);
        }
    });
    

    섬기는 사람

    def urll(request):
    
    if request.is_ajax():
        if request.method == 'POST':
            print ('Raw Data:', request.body) 
    
            print ('type(request.body):', type(request.body)) # this type is bytes
    
            print(json.loads(request.body.decode("utf-8")))
    
  7. ==============================

    7.HTTP POST 페이로드는 단순한 바이트 묶음입니다. Django (대부분의 프레임 워크와 마찬가지로)는 URL로 인코딩 된 매개 변수 또는 MIME-multipart 인코딩에서 사전을 디코딩합니다. POST 컨텐트에 JSON 데이터를 덤프하면 장고는 디코딩하지 않습니다. JSON 디코딩을 전체 POST 컨텐츠 (사전이 아님)에서 수행하십시오. 또는 JSON 데이터를 MIME 멀티 파트 래퍼에 넣을 수 있습니다.

    HTTP POST 페이로드는 단순한 바이트 묶음입니다. Django (대부분의 프레임 워크와 마찬가지로)는 URL로 인코딩 된 매개 변수 또는 MIME-multipart 인코딩에서 사전을 디코딩합니다. POST 컨텐트에 JSON 데이터를 덤프하면 장고는 디코딩하지 않습니다. JSON 디코딩을 전체 POST 컨텐츠 (사전이 아님)에서 수행하십시오. 또는 JSON 데이터를 MIME 멀티 파트 래퍼에 넣을 수 있습니다.

    요컨대, JavaScript 코드를 보여주십시오. 문제가 거기에있는 것 같습니다.

  8. ==============================

    8.request.raw_post_data는 더 이상 사용되지 않습니다. 대신 request.body 사용

    request.raw_post_data는 더 이상 사용되지 않습니다. 대신 request.body 사용

  9. ==============================

    9.

    html code 
    
    file name  : view.html
    
    
        <!DOCTYPE html>
        <html>
        <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
        $(document).ready(function(){
            $("#mySelect").change(function(){
                selected = $("#mySelect option:selected").text()
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    url: '/view/',
                    data: {
                           'fruit': selected
                          },
                    success: function(result) {
                            document.write(result)
                            }
            });
          });
        });
        </script>
        </head>
        <body>
    
        <form>
            <br>
        Select your favorite fruit:
        <select id="mySelect">
          <option value="apple" selected >Select fruit</option>
          <option value="apple">Apple</option>
          <option value="orange">Orange</option>
          <option value="pineapple">Pineapple</option>
          <option value="banana">Banana</option>
        </select>
        </form>
        </body>
        </html>
    
    Django code:
    
    
    Inside views.py
    
    
    def view(request):
    
        if request.method == 'POST':
            print request.body
            data = request.body
            return HttpResponse(json.dumps(data))
    
  10. ==============================

    10.이 같은. 효과가 있습니다. 클라이언트로부터 데이터 요청

    이 같은. 효과가 있습니다. 클라이언트로부터 데이터 요청

    registerData = {
    {% for field in userFields%}
      {{ field.name }}: {{ field.name }},
    {% endfor %}
    }
    
    
    var request = $.ajax({
       url: "{% url 'MainApp:rq-create-account-json' %}",
       method: "POST",
       async: false,
       contentType: "application/json; charset=utf-8",
       data: JSON.stringify(registerData),
       dataType: "json"
    });
    
    request.done(function (msg) {
       [alert(msg);]
       alert(msg.name);
    });
    
    request.fail(function (jqXHR, status) {
      alert(status);
    });
    

    서버에서 요청 처리

    @csrf_exempt
    def rq_create_account_json(request):
       if request.is_ajax():
           if request.method == 'POST':
               json_data = json.loads(request.body)
               print(json_data)
               return JsonResponse(json_data)
       return HttpResponse("Error")
    
  11. ==============================

    11.Angular를 사용하면 헤더를 추가하여 모듈 설정에 추가하거나 추가해야합니다. 헤더 : { 'Content-Type': 'application / x-www-form-urlencoded'}

    Angular를 사용하면 헤더를 추가하여 모듈 설정에 추가하거나 추가해야합니다. 헤더 : { 'Content-Type': 'application / x-www-form-urlencoded'}

    $http({
        url: url,
        method: method,
        timeout: timeout,
        data: data,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    
  12. ==============================

    12.request.POST는 사전과 같은 객체이므로 dict 구문을 사용하여 색인을 작성하면됩니다.

    request.POST는 사전과 같은 객체이므로 dict 구문을 사용하여 색인을 작성하면됩니다.

    양식 필드가 fred라고 가정하면 다음과 같이 할 수 있습니다.

    if 'fred' in request.POST:
        mydata = request.POST['fred']
    

    또는 POST 데이터를 처리하기 위해 양식 객체를 사용하십시오.

  13. from https://stackoverflow.com/questions/1208067/wheres-my-json-data-in-my-incoming-django-request by cc-by-sa and MIT license