1

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Its a dict access it like this:

if x['code'] == 2:

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.