Django中的response

render_to_response

render_to_response('index.html', locals(),context_instance=RequestContext(request))

参数顺序:(template_name, dictionary=None, context_instance=None)

在django模板系统中,有两种封装模板变量的类,一个是django.template.Context,这是最常用的,我们在使用render_to_response方法的时候传入的第二个dictionary参数,就会被这个Context类封装一次,然后传到模板当中。

另一个是django.template.RequestContext,它和Context类相比有两个不同之处。

第一个不同的是,在生成一个RequestContext变量的时候,需要传入一个HttpRequest对象作为它的第一个参数。

其次,它会增加一些自动注入模板的变量,这些变量由settings中的TEMPLATE_CONTEXT_PROCESSORS中声明的方法返回,TEMPLATE_CONTEXT_PROCESSORS中的方法都接收一个HttpRequest对象,最终return一个dict。这个dictionary里面的元素就会成为RequestContext中自动注入模板的变量。比如django.contrib.auth.context_processors.auth就会返回user、messages、perms变量

# in django/contrib/auth/context_processors.py
def auth(request):
    """ ignore doc string """
    def get_user():
        ....
 
    return {
        'user': SimpleLazyObject(get_user),
        'messages': messages.get_messages(request),
        'perms':  lazy(lambda: PermWrapper(get_user()), PermWrapper)(),
    }

有时候会用到dictionary=locals()这种操作,这是将当前域的所有局部变量都赋给dictionary

Response与HttpResponse的区别

  • HttpResponse

    # django/http/response.py
    # HttpResponse的初始化
    class HttpResponseBase(six.Iterator):
        def __init__(self, content_type=None, status=None, reason=None, charset=None):
    
    class HttpResponse(HttpResponseBase):
        def __init__(self, content=b'', *args, **kwargs):
            super(HttpResponse, self).__init__(*args, **kwargs)
            # Content is a bytestring. See the `content` property methods.
            self.content = content
    
    • HttpResponse对象由Django创建,常用于函数式视图
    • super()常用于调用父类的方法。
      super(HttpResponse, self).__init__(*args, **kwargs)
      
      即调用HttpResponse父类HttpResponseBase的__init__方法
    • 因此,HttpResponse生成格式为HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)
    • 注意如果前端需要json数据类型,而data是一个字典,则需要手动把data转为json格式。HttpResponse(json.dumps(data))
  • Response

    # rest_framework/response.py
    # Response的初始化
    class Response(SimpleTemplateResponse):
        def __init__(self, data=None, status=None,
                     template_name=None, headers=None,
                     exception=False, content_type=None):
    
    • Response对象是Django REST framework框架封装的对象

    • Response会自动将传入data的数据转为json,无需手动转换。甚至可以直接Response(data=serializer.data)

    • 一般在DRF框架中类的视图中使用Response对象,类的视图要继承APIView

    • 如果要在函数式视图使用Response,需要加上@api_view装饰器,如

      from rest_framework.decorators import api_view
      
      @api_view(['GET', 'POST', ])
      def articles(request, format=None):
          data= {'articles': Article.objects.all() }
          return Response(data, template_name='articles.html')
      

      如果不加装饰器的话,会报错:“.accepted_renderer not set on Response”

posted @ 2019-06-03 16:52  luozx207  阅读(3493)  评论(0编辑  收藏  举报