如何将httpresponse对象转换为字典

时间:2016-01-07 08:58:49

标签: python dictionary response httpresponse

首先,我很抱歉,因为我的问题是重复的,但实际上对方根本不适用于我。

我的问题是我有2个视图,第一个返回Httpresponse到第2个,我想要的是在第二个视图中将此Httpresponse转换为字典并且可以访问它的元素。

这是代码:

第一个观点:

def base_tag_upload(request, tag):

error = False
upload_msg = "success"
user = request.user
response_data = {"error": error, "upload_msg": upload_msg, "file_id": None, "file_version": None}

if request.method == 'POST':
    form = UploadForm(request.POST or None, request.FILES or None, tag=tag, user=user)
    if form.is_valid():
        cd = form.cleaned_data
        uploaded_file = cd['file']
        collection_name = cd['new_name'] or uploaded_file.name.split('.')[0].strip()
        response_data.update(
            {"uf_name": uploaded_file.name, "uf_size": uploaded_file.size, "uf_colname": collection_name})
        set_primary = True  # first file in collection

        # Finding/Creating Related FileCollection
        collection = FileCollection.objects.create(name=collection_name)
        is_major = cd['version_type'] == 'mj'
        file_obj = collection.upload_file(uploaded_file, set_primary, Major_version=is_major)
        file_obj.author = user
        collection.tags.add(tag)
        collection.get_tag_permissions(tag, False)
        file_obj.get_collection_permissions(collection, False)
        set_user_ownership(collection, tag, user)
        set_user_ownership(file_obj, tag, user)

        collection.save()
        file_obj.collection = collection
        file_obj.save()
        response_data.update({'file_id':file_obj.id, 'file_version': file_obj.version})
        ActionLog.log(action=Action.objects.get(name="create"), target=file_obj,
                      user=user, request=request, details=None, extra_details=None)
        redirect_url = reverse('file_history', kwargs={'collection_id': collection.id})
        response_data.update({'redirect': redirect_url})
        return HttpResponse(json.dumps([response_data]))

和第二个:

def tag_upload(request, tag_id):
try:
    tag = Tag.objects.get(id=tag_id)
except Tag.DoesNotExist:
    return HttpResponse(simplejson.dumps([{'error': 'value_error', 'upload_msg': "no such folder"}]))
k = base_tag_upload(request, tag)
k.response.decode('utf-8')
print k
return base_tag_upload(request, tag)

但是当我想解码Httpresponse时,我得到了这个错误,如上所示:

AttributeError: 'HttpResponse' object has no attribute 'response'

2 个答案:

答案 0 :(得分:1)

  

我有2个视图,第一个视图返回Httpresponse到第二个

然后你没有正确构建你的代码 - 一个视图没有业务调用另一个视图而不会弄乱响应。

如果你需要在两个视图之间共享一些公共代码,那么在一个不同的函数中提取这个代码(在这种情况下会返回一个简单的dict)并从你的两个视图中调用这个函数。

答案 1 :(得分:0)

这是k.content.decode('utf-8')