如何从HttpResponse中获取实际值?

时间:2015-01-20 15:30:47

标签: python django django-views

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

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

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

并返回一个HttpResponse对象,如何获得status值?

2 个答案:

答案 0 :(得分:1)

所以你要说的是你需要从你的google函数返回两个东西(一个HttpResponse和状态值)而不是一件事。

在这种情况下,你应该返回一个元组,例如:

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

答案 1 :(得分:0)

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 }}