简体   繁体   中英

How to get actual value from HttpResponse in view?

Views.py

def process_view(request):
    dspAction = {}
    try:
        google = google(objectId) #google = google(requst, objectId)
        if google['status'] == int(1):
            #some function
    except:
        dspAction['Google Status'] = "Google Action Completed"
    return HttpResponse(json.dumps(dspAction),content_type='application/json')

The above function is pretty basic and it's working very well with this google function:

def google(objectId):
    googelAction = {}
    google['status'] = 1
    return google

But for some reason I want request in google function. If I do this:

def google(request, objectId):
    googelAction = {}
    google['status'] = 1
    return HttpResponse(google)

and return a HttpResponse object, how can I get the status value ?

So what you are saying is you need to return two things (an HttpResponse and the status value) from your google function instead of just one thing.

In this case you should return a tuple, eg:

def google(request, objectId):
    google = {}
    google['status'] = 1
    response = HttpResponse(json.dumps(google))  # <-- should be string not dict
    return response, google

def process_view(request):
    dspAction = {}
    try:
        response, google = google(request, objectId)
        if google['status'] == int(1):
            #some function
    except:
        dspAction['Google Status'] = "Google Action Completed"
    return HttpResponse(json.dumps(dspAction),content_type='application/json')

return HttpResponse(google.status)

EDIT from comment: To use the other attributes in the dictionary you need to pass the context variables, usually with render.

# view.py
from django.shortcuts import render
... 
return render(request, "template.html", {'google':google})


# template.html
# you can then access the different attributes of the dict
{{ google }} {{ google.status }} {{ google.error }} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM