如何从视图中的 HttpResponse 获取实际值?

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')

上面的函数非常基础,它与这个 google 函数一起工作得很好:

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

但出于某种原因,我想在 google 函数中使用 request。如果我这样做:

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

和 return 一个 HttpResponse 对象,如何获取 status 值?

return HttpResponse(google.status)

根据评论编辑: 要使用字典中的其他属性,您需要传递上下文变量,通常使用 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 }} 

所以你的意思是你需要从你的 google 函数中 return 两件事(一个 HttpResponse 和状态值)而不是一件事。

在这种情况下,您应该 return 一个元组,例如:

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')