Get request body as string in Django

前端 未结 3 1641
旧时难觅i
旧时难觅i 2020-12-01 17:45

I\'m sending a POST request with JSON body to a Django server (fairly standard). On the server I need to decode this using json.loads().

The problem is

相关标签:
3条回答
  • 2020-12-01 18:20

    The request body, request.body, is a byte string. In Python 3, json.loads() will only accept a unicode string, so you must decode request.body before passing it to json.loads().

    body_unicode = request.body.decode('utf-8')
    body_data = json.loads(body_unicode)
    

    In Python 2, json.loads will accept a unicode string or a byte sting, so the decode step is not necessary.

    When decoding the string, I think you're safe to assume 'utf-8' - I can't find a definitive source for this, but see the quote below from the jQuery docs:

    Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.

    In Python 3.6, json.loads() accepts bytes or bytearrays. Therefore you shouldn't need to decode request.body (assuming it's encoded in UTF-8).

    0 讨论(0)
  • 2020-12-01 18:39

    If your goal is to end up with a dictionary of the data you have just sent to the server using JSON, save yourself the trouble of decoding the body yourself and use the request.POST dictionary-like object django already provides out-of-the-box.

    So suppose you POST this to the server:

    { 'foo': 'bar' }
    

    Then the following method

    def my_handler(request):
        foo = request.POST['foo']
        print(foo)
    

    Would print bar to the console

    0 讨论(0)
  • 2020-12-01 18:41

    I believe that the other end from where you receive this request does not convert the data to JSON before sending the request. Either you have to convert the data to JSON before you send, or just try accessing request.body in your view.

    0 讨论(0)
提交回复
热议问题