django源码分析-http模块分析


django http模块实现django的网络功能,实现请求(HttpRequest)和响应(HttpResponse),我们视图中的request参数和返回的response对象,就来自这个模块。该模块的内容如下:

  • init.py : django http模块初始化文件,实现导入。
from django.http.cookie import SimpleCookie, parse_cookie
from django.http.request import (
    HttpRequest, QueryDict, RawPostDataException, UnreadablePostError,
)
from django.http.response import (
    BadHeaderError, FileResponse, Http404, HttpResponse,
    HttpResponseBadRequest, HttpResponseForbidden, HttpResponseGone,
    HttpResponseNotAllowed, HttpResponseNotFound, HttpResponseNotModified,
    HttpResponsePermanentRedirect, HttpResponseRedirect,
    HttpResponseServerError, JsonResponse, StreamingHttpResponse,
)

__all__ = [
    'SimpleCookie', 'parse_cookie', 'HttpRequest', 'QueryDict',
    'RawPostDataException', 'UnreadablePostError',
    'HttpResponse', 'StreamingHttpResponse', 'HttpResponseRedirect',
    'HttpResponsePermanentRedirect', 'HttpResponseNotModified',
    'HttpResponseBadRequest', 'HttpResponseForbidden', 'HttpResponseNotFound',
    'HttpResponseNotAllowed', 'HttpResponseGone', 'HttpResponseServerError',
    'Http404', 'BadHeaderError', 'JsonResponse', 'FileResponse',
]
  • cookie.py : 实现cookie的解析。
from http import cookies

# For backwards compatibility in Django 2.1.
SimpleCookie = cookies.SimpleCookie

# Add support for the SameSite attribute (obsolete when PY37 is unsupported).
cookies.Morsel._reserved.setdefault('samesite', 'SameSite')


def parse_cookie(cookie):
    """
    Return a dictionary parsed from a `Cookie:` header string.
    """
    cookiedict = {}
    for chunk in cookie.split(';'):
        if '=' in chunk:
            key, val = chunk.split('=', 1)
        else:
            # Assume an empty name per
            # https://bugzilla.mozilla.org/show_bug.cgi?id=169091
            key, val = '', chunk
        key, val = key.strip(), val.strip()
        if key or val:
            # unquote using Python's algorithm.
            cookiedict[key] = cookies._unquote(val)
    return cookiedict
  • multipartparser.py : 实现对django图片文件上传的解析。
  • request.py : 该模块是 HttpRequest 类的实现,用来实现django处理http请求。
  • response.py : 该模块是 HttpResponse 类的实现,用来实现返回django http响应。就是试图函数或者试图类的返回值。

更多Django教程

学习更多Django教程