Reputation: 653
i am using this code to make an api which return the post request so i can test and modify them according to my needs.
I have tried two codes by searching on SO.
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt
def some_view(request, username):
json_data = json.dumps(request)
return JsonResponse(json_data, safe=False)
This code give me the error of is not JSON serializable
.
If i applied a list attribute to it. Like
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt
def some_view(request, username):
json_data = json.dumps(list(request))
return HttpResponse(json_data)
it did not give me an error but return the empty output.[]
Edit: if i tried to return request.POST
. I got a empty array.
I am testing this api through POSTMAN
.
Upvotes: 0
Views: 2084
Reputation: 790
If you want to read Request
object attributes, you can use request.__dict__
.
This will return you serailizable object something like
{
'FILES': < MultiValueDict: {} > ,
'COOKIES': {},
'_post_parse_error': False,
'resolver_match': None,
'GET': < QueryDict: {} > ,
'META': {},
'path_info': u '',
'path': u '',
'POST': < QueryDict: {} > ,
'method': None
}
You may need to iterate over and read __dict__
attributes of nested objects too, such as 'GET': <QueryDict: {}>
, 'POST': <QueryDict: {}>
.
Upvotes: 0
Reputation: 31494
request
is a HttpRequest
object - not the raw request body. You need to access that with request.body
. You probably also want to use JsonResponse
instead of HttpResponse
if you want to return JSON via a Python object:
request_data = json.loads(request.body.decode('utf-8')) # This assumes your request body is JSON
json_data = json.dumps(request_data)
return JsonResponse(json_data)
(I'm assuming that you will do a bit more that just returning the original request later on).
Upvotes: 2