In Django response

render_to_response

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

Parameter order: (template_name, dictionary = None, context_instance = None)

In django template system, there are two packages class template variables, one django.template.Context, this is the most commonly used, we pass when using the second method render_to_response dictionary parameter, it will be this Context a type of packaging, which then passes the template.

Another is django.template.RequestContext, Context class and compared it with two differences.

The first difference is that, in RequestContext generate a variable time, need to pass an HttpRequest object as its first argument.

Second, it will increase the number of variables automatically injected into the template, these variables returned by the method settings in TEMPLATE_CONTEXT_PROCESSORS declared, the method TEMPLATE_CONTEXT_PROCESSORS receives an HttpRequest object, and ultimately return a dict. The dictionary elements inside will become variable RequestContext automatically injected into the template. For example django.contrib.auth.context_processors.auth will return user, messages, perms variable

# 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)(),
    }

Sometimes used dictionary = locals () This operation, which is all the local variables of the current domain are assigned to dictionary

Response to the difference between the 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 object is created by Django, commonly used functional view
    • super () method commonly used to call the parent class.
      python super(HttpResponse, self).__init__(*args, **kwargs)
      That call __init__ method of the HttpResponse parent HttpResponseBase
    • Thus, HttpResponse in format HttpResponse (content = response body, content_type = volume data type, status = status code response)
    • Note that if needed the front end json data type, a data dictionary, the data will need to manually into json format. 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 object Django REST framework is encapsulated object frame
    • Response will automatically pass data into the data json, without manual conversion. Even directly Response (data = serializer.data)
    • Is generally used in view DRF Response object class in the framework, the view class to inherit APIView
    • In Response To use functional view, the need to add @api_view decoration, such as

      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')

      If not a decorator, then, will complain: ". Accepted_renderer not set on Response"

Guess you like

Origin www.cnblogs.com/luozx207/p/10968572.html