Django框架-源碼-01三板斧和JsonRespon源碼剖析

HttpResponse

class HttpResponse(HttpResponseBase):    
    """    An HTTP response class with a string as content.    This content that can be read, appended to or replaced.    """    
    streaming = False    
    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

return HttpResponse("hello world")html

本質返回的就是HttpResponse對象python

render

def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Returns a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)

return render(request, "login.html", local())django

發現本質仍是 HttpResponse來處理數據, 最終返回的仍是HttpResponse對象json

redirect

def redirect(to, *args, **kwargs):
    """
    Returns an HttpResponseRedirect to the appropriate URL for the arguments
    passed.

    The arguments could be:

        * A model: the model's `get_absolute_url()` function will be called.

        * A view name, possibly with arguments: `urls.reverse()` will be used
          to reverse-resolve the name.

        * A URL, which will be used as-is for the redirect location.

    By default issues a temporary redirect; pass permanent=True to issue a
    permanent redirect
    """
    if kwargs.pop('permanent', False):
        redirect_class = HttpResponsePermanentRedirect
    else:
        redirect_class = HttpResponseRedirect

    return redirect_class(resolve_url(to, *args, **kwargs))

return redirect("/home.html")app

返現最後調用了 redirect_class, 可是它指向的依然是HttpResponse對象編碼

總結:

全部請求都會返回一個HttpResponse是對的!url

本質 render, redirect源碼裏面返回的都是HttpResponsecode

JsonResponse

from django.http imoprt JsonResponsehtm

def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super(JsonResponse, self).__init__(content=data, **kwargs)

這邊對於參數 safe, json_dumps__params對象

能夠發現 JsonResponse本值仍是調用了 data = json.dumps(data, cls=encoder, **json_dumps_params)

對應 json_dumps__params 是爲了解決相關的 中文編碼不能正常顯示問題 設置爲key, value 方式傳入參數就能夠解決 json_dumps_params={"ensure_ascii":"False"}

對應 list 數據不能JsonResponse報錯狀況, 能夠設置 safe=False 解決問題 ,取決於源碼裏的判斷

if safe and not isinstance(data, dict):

相關文章
相關標籤/搜索