【问题标题】:Django: how to add http header to responses in a convenient way?Django:如何以方便的方式将 http 标头添加到响应中?
【发布时间】:2016-04-06 11:13:46
【问题描述】:

我知道我们可以使用 HttpResponseInstance['headername'] = 'headervalue' 将标头添加到 http 响应。但是这样一来,我必须重写我正在使用的所有通用视图,这会带来更多的工作。

是否有一种方便的方法可以将标头添加到响应中,例如响应的回调或 url 装饰器?

【问题讨论】:

    标签: python django http web


    【解决方案1】:

    您可以编写一个middleware 类并实现方法process_response。

    【讨论】:

      【解决方案2】:

      您应该使用中间件类。 Check out this thread.

      Django 1.10 及以上版本__init__ 和__call__ 应该被实现。 process_response 已弃用。

      【讨论】:

        【解决方案3】:

        在返回 JsonResponse 时添加一些自定义标头。

        from django.http import JsonResponse
        
        data = {'key','value'} # some data
        
        response = JsonResponse(data,status=200)
        
        response['Retry-after'] = 345 # seconds 
        response['custom-header'] = 'some value'
        
        return response 
        

        【讨论】:

          猜你喜欢
          • 2021-02-17
          • 2016-04-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-19
          • 2013-12-19
          • 1970-01-01
          相关资源
          最近更新 更多