Django中的response

render_to_response

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

參數順序:(template_name, dictionary=None, context_instance=None)html

在django模板系統中,有兩種封裝模板變量的類,一個是django.template.Context,這是最經常使用的,咱們在使用render_to_response方法的時候傳入的第二個dictionary參數,就會被這個Context類封裝一次,而後傳到模板當中。前端

另外一個是django.template.RequestContext,它和Context類相比有兩個不一樣之處。python

第一個不一樣的是,在生成一個RequestContext變量的時候,須要傳入一個HttpRequest對象做爲它的第一個參數。django

其次,它會增長一些自動注入模板的變量,這些變量由settings中的TEMPLATE_CONTEXT_PROCESSORS中聲明的方法返回,TEMPLATE_CONTEXT_PROCESSORS中的方法都接收一個HttpRequest對象,最終return一個dict。這個dictionary裏面的元素就會成爲RequestContext中自動注入模板的變量。好比django.contrib.auth.context_processors.auth就會返回user、messages、perms變量json

# 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()這種操做,這是將當前域的全部局部變量都賦給dictionaryapi

Response與HttpResponse的區別

  • HttpResponseapp

    # 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()經常使用於調用父類的方法。
      python 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」rest

相關文章
相關標籤/搜索