【问题标题】:Add custom data in Response() of django rest framework while GET?在 GET 时在 django rest 框架的 Response() 中添加自定义数据?
【发布时间】:2018-02-12 10:29:40
【问题描述】:

我正在使用Django rest framework,我必须在Response() 对象中添加我的自定义数据。

rsp = Response()
rsp['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(file)
rsp['X-Accel-Redirect'] = '/export/%s' % file

我想在这个Response()的数据部分添加custome dict

因此我尝试了这个,

data = {'length': 10}
rsp = Response(data)

data = {'length': 10}
rsp = Response()
rsp['data'] = data

但我收到了'error:{'data'}' 的错误

帮助我了解为什么会发生这种行为以及如何在Response() 中添加自定义数据

【问题讨论】:

    标签: python django django-rest-framework response


    【解决方案1】:

    当您设置rsp['data'] 时,它正在尝试设置标题。这会产生错误,因为 data 是字典,而不是字符串。

    相反,您应该在初始化响应时将响应数据作为第一个参数传递:

    from rest_framework.response import Response
    
    data = {'length': 10}
    rsp = Response(data)
    ...
    

    【讨论】:

    • 感谢@Alasdair 的快速回复,我也尝试了这种方法,但是当我在做hasattr(response, 'data') 时,它返回False,而且我的数据也无法回收
    • 如果我做rsp = Response(data),那么hasattr(rsp, 'data') 会返回True 并且rsp.data 会给出字典。
    • 你能告诉我,我可能犯了什么错误,将这种行为归还给我@Alasdair
    • 除非你能给出一个重现问题的例子,否则很难再提供帮助了。
    • 是的,没关系,是否有任何场景或实现强制这种行为,或者您以前遇到过这种情况?
    【解决方案2】:
    data = {'length': 10}
    return Response({'data': data})
    

    所以;

    response = {}
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(file)
    response['X-Accel-Redirect'] = '/export/%s' % file
    return Response(response)
    

    【讨论】:

    • 您能否提供有关答案的更多详细信息?
    • 是的,我也看不懂
    • @origamic 你能详细了解你的解决方案吗
    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 2016-05-03
    • 2021-11-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多