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 how do I get the body of the request in a string format?
I have the following code currently:
body_data = {}
if request.META.get('CONTENT_TYPE', '').lower() == 'application/json' and len(request.body) > 0:
try:
body_data = json.loads(request.body)
except Exception as e:
return HttpResponseBadRequest(json.dumps({'error': 'Invalid request: {0}'.format(str(e))}), content_type="application/json")
However, this gives an error the JSON object must be str, not 'bytes'
.
How do I retrieve the body of the request as a string, with the correct encoding applied?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…