Reputation: 1731
I have a function getCode
that is called from ajax and returns HttpResponse(json.dumps({'code': 2}))
. I have one case where this function is called from inside another Python function in an effort to stick to DRY. I am trying to access the HttpResponse in an if
statement in this other function like so:
x = getCode(request)
if x['code'] == 2:
# do stuff
How do I parse the HttpResponse object in Python so that I can access the data within as a dict?
Upvotes: 1
Views: 1242
Reputation: 33
First get request.
x = getCode(request)
Convert the response to string.
string_data = r.getresponse().read().decode("utf-8")
Convert the string to dict.
dict_data = json.loads(string_data)
Upvotes: 0
Reputation: 473873
It doesn't really sound good and correct to have an overhead of creating an HttpResponse
and to call the view from other python function. A code design and structure problem here.
Extract the logic that produces the data in the view into the separate function:
def my_view(request):
data = get_data()
return HttpResponse(json.dumps(data), mimetype='application/json')
Then, call the function directly, not the view:
x = get_data()
if x['code'] == 2:
...
This way you would not need to first dump the data to JSON
, make an HttpResponse
, load the response content into the python data structure again.
Hope that makes sense for you.
Upvotes: 1