Django源码分析5:session会话中间件分析

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_33339479/article/details/79213169

django源码分析

本文环境python3.5.2,django1.10.x系列

1.这次分析django框架中的会话中间件。
2.会话保持是目前框架都支持的一个功能,因为http是无状态协议,无法直接报错请求过程中的数据,会话保持就是要实现会话数据保存的功能,实现数据在服务端的保存,目前会话的实现的主要途径就是通过cookie来进行会话的保持。
3.大致浏览功能后我们分析一下Django框架中的会话的实现。

分析

1.首先需要在配置文件中配置,

 INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

SESSION_ENGINE = 'django.contrib.sessions.backends.db'

配置到app中,主要是为了让app能够管理会话的数据库,当不配置的时候就是使用默认的数据库存储;配置到MIDDLEWARE是为了让会话的实现。
首先分析一下django.contrib.sessions.middleware.SessionMiddleware的代码

class SessionMiddleware(MiddlewareMixin):
    def __init__(self, get_response=None):
        self.get_response = get_response
        engine = import_module(settings.SESSION_ENGINE)                                 # 导入配置文件中的session引擎
        self.SessionStore = engine.SessionStore

    def process_request(self, request):
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)                 # 先获取配置文件中设置的cookie名称,然后根据名称获取request中的对应的值
        request.session = self.SessionStore(session_key)                                # 初始化request的session

    def process_response(self, request, response):
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie or delete
        the session cookie if the session has been emptied.
        """
        try:
            accessed = request.session.accessed
            modified = request.session.modified
            empty = request.session.is_empty()
        except AttributeError:
            pass
        else:
            # First check if we need to delete this cookie.
            # The session should be deleted only if the session is entirely empty
            if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:               # 判断cookie中是否带着对应头部cookie并且session为空
                response.delete_cookie(                                                 # 删除cookie
                    settings.SESSION_COOKIE_NAME,
                    path=settings.SESSION_COOKIE_PATH,
                    domain=settings.SESSION_COOKIE_DOMAIN,
                )
            else:
                if accessed:
                    patch_vary_headers(response, ('Cookie',))
                if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
                    if request.session.get_expire_at_browser_close():                   # 是否设置浏览器关闭就session过期
                        max_age = None
                        expires = None
                    else:
                        max_age = request.session.get_expiry_age()                      # 获取session的最大保持时间
                        expires_time = time.time() + max_age                            # 当前的时间加上最大过期时间,默认为两周
                        expires = cookie_date(expires_time)                             # 将过期时间转换为cookie的设置格式
                    # Save the session data and refresh the client cookie.
                    # Skip session save for 500 responses, refs #3881.
                    if response.status_code != 500:                                     # 如果处理返回结果不是500,则重新刷新cookie的过期时间
                        try:
                            request.session.save()                                      # 保存会话
                        except UpdateError:
                            raise SuspiciousOperation(
                                "The request's session was deleted before the "
                                "request completed. The user may have logged "
                                "out in a concurrent request, for example."
                            )
                        response.set_cookie(                                            # 通过respnose设置返回cookie的时间等信息
                            settings.SESSION_COOKIE_NAME,
                            request.session.session_key, max_age=max_age,
                            expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                            path=settings.SESSION_COOKIE_PATH,
                            secure=settings.SESSION_COOKIE_SECURE or None,
                            httponly=settings.SESSION_COOKIE_HTTPONLY or None,
                        )
        return response

主要是通过获取cookie的默认的sessionid值来获取会话的值,该中间价主要是在请求处理之前,通过sessionid的值去相应的会话引擎中获取根据该值保持的数据,当处理完成后,通过更新设置的cookie对应的sessionid的时间来重新设置会话保持的时间。
框架提供了db,file,cache_db,cache的方式来实现会话。
这里只分析db,file,cache这三种方式的实现方式。
因为这几种会话都是继承自一个SessionBase值。

class SessionBase(object):
    """
    Base class for all Session classes.
    """
    TEST_COOKIE_NAME = 'testcookie'
    TEST_COOKIE_VALUE = 'worked'

    __not_given = object()

    def __init__(self, session_key=None):
        self._session_key = session_key                                     # 设置回话key,该值是从cookie中获取得到
        self.accessed = False                                               # 访问时间
        self.modified = False                                               # 修改时间
        self.serializer = import_string(settings.SESSION_SERIALIZER)        # 设置序列化对象

    def __contains__(self, key):
        return key in self._session                                         # 数据中是否有该值

    def __getitem__(self, key):
        return self._session[key]                                           # 获取对应key值

    def __setitem__(self, key, value):
        self._session[key] = value                                          # 设置key的value
        self.modified = True

    def __delitem__(self, key):
        del self._session[key]                                              # 删除key对应的value
        self.modified = True

    def get(self, key, default=None):
        return self._session.get(key, default)                              # 获取对应值

    def pop(self, key, default=__not_given):
        self.modified = self.modified or key in self._session               # 判断
        args = () if default is self.__not_given else (default,)
        return self._session.pop(key, *args)

    def setdefault(self, key, value):                                       # 设置默认值
        if key in self._session:
            return self._session[key]                                       # 返回存储的值
        else:
            self.modified = True
            self._session[key] = value                                      # 否则设置该值
            return value

    def set_test_cookie(self):
        self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE                # 设置测试会话值

    def test_cookie_worked(self):
        return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE    # 测试会话值是否正确

    def delete_test_cookie(self):
        del self[self.TEST_COOKIE_NAME]                                     # 删除测试会话值

    def _hash(self, value):
        key_salt = "django.contrib.sessions" + self.__class__.__name__      # 哈希value
        return salted_hmac(key_salt, value).hexdigest()

    def encode(self, session_dict):
        "Returns the given session dictionary serialized and encoded as a string."
        serialized = self.serializer().dumps(session_dict)                              # 序列化该值
        hash = self._hash(serialized)                                                   # 设置hash值
        return base64.b64encode(hash.encode() + b":" + serialized).decode('ascii')      # 编码生成值

    def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))                      # 解码该值
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                logger.warning(force_text(e))
            return {}

    def update(self, dict_):
        self._session.update(dict_)
        self.modified = True

    def has_key(self, key):
        return key in self._session

    def keys(self):
        return self._session.keys()

    def values(self):
        return self._session.values()

    def items(self):
        return self._session.items()

    def iterkeys(self):
        return self._session.iterkeys()

    def itervalues(self):
        return self._session.itervalues()

    def iteritems(self):
        return self._session.iteritems()

    def clear(self):
        # To avoid unnecessary persistent storage accesses, we set up the
        # internals directly (loading data wastes time, since we are going to
        # set it to an empty dict anyway).
        self._session_cache = {}                                                # 清除所有数据
        self.accessed = True
        self.modified = True

    def is_empty(self):
        "Returns True when there is no session_key and the session is empty"
        try:
            return not bool(self._session_key) and not self._session_cache      # 只要有任意一个属性则不为空
        except AttributeError:
            return True                                                         # 如果没有其中_session_key或者_session_cache任一一个属性则为空

    def _get_new_session_key(self):
        "Returns session key that isn't being used."
        while True:
            session_key = get_random_string(32, VALID_KEY_CHARS)                # 获取session的key值,
            if not self.exists(session_key):                                    # 检查key是否存在,直到不重复为止
                break
        return session_key

    def _get_or_create_session_key(self):
        if self._session_key is None:                                           # 如果session_key为空就生成
            self._session_key = self._get_new_session_key()
        return self._session_key

    def _validate_session_key(self, key):
        """
        Key must be truthy and at least 8 characters long. 8 characters is an
        arbitrary lower bound for some minimal key security.
        """
        return key and len(key) >= 8                                            # 检查key是否合法

    def _get_session_key(self):
        return self.__session_key

    def _set_session_key(self, value):
        """
        Validate session key on assignment. Invalid values will set to None.
        """
        if self._validate_session_key(value):
            self.__session_key = value
        else:
            self.__session_key = None

    session_key = property(_get_session_key)
    _session_key = property(_get_session_key, _set_session_key)

    def _get_session(self, no_load=False):
        """
        Lazily loads session from storage (unless "no_load" is True, when only
        an empty dict is stored) and stores it in the current instance.
        """
        self.accessed = True                                                        # 设置访问为真
        try:
            return self._session_cache                                              # 先尝试获取该属性
        except AttributeError:                                                      # 如果获取该属性失败
            if self.session_key is None or no_load:                                 # 如果no_load或者session_key为none为真,则置空
                self._session_cache = {}
            else:
                self._session_cache = self.load()                                   # 否则重新加载,该方法由子类实现
        return self._session_cache                                                  # 返回该属性

    _session = property(_get_session)

    def get_expiry_age(self, **kwargs):
        """Get the number of seconds until the session expires.

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError: 
            modification = timezone.now()                                           # 如果没有就设置为当前时间
        # Make the difference between "expiry=None passed in kwargs" and
        # "expiry not passed in kwargs", in order to guarantee not to trigger
        # self.load() when expiry is provided.
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if not expiry:   # Checks both None and 0 cases
            return settings.SESSION_COOKIE_AGE                                      # 如果输入参数中没有两个参数,则返回配置文件中的默认值
        if not isinstance(expiry, datetime):
            return expiry
        delta = expiry - modification
        return delta.days * 86400 + delta.seconds                                   # 返回还剩余过期的时间

    def get_expiry_date(self, **kwargs):
        """Get session the expiry date (as a datetime object).

        Optionally, this function accepts `modification` and `expiry` keyword
        arguments specifying the modification and expiry of the session.
        """
        try:
            modification = kwargs['modification']
        except KeyError:
            modification = timezone.now()
        # Same comment as in get_expiry_age
        try:
            expiry = kwargs['expiry']
        except KeyError:
            expiry = self.get('_session_expiry')

        if isinstance(expiry, datetime):
            return expiry
        if not expiry:   # Checks both None and 0 cases
            expiry = settings.SESSION_COOKIE_AGE
        return modification + timedelta(seconds=expiry)                             # 返回cookie过期的具体日期

    def set_expiry(self, value):
        """
        Sets a custom expiration for the session. ``value`` can be an integer,
        a Python ``datetime`` or ``timedelta`` object or ``None``.

        If ``value`` is an integer, the session will expire after that many
        seconds of inactivity. If set to ``0`` then the session will expire on
        browser close.

        If ``value`` is a ``datetime`` or ``timedelta`` object, the session
        will expire at that specific future time.

        If ``value`` is ``None``, the session uses the global session expiry
        policy.
        """
        if value is None:                                                           # 如果传入none,则删除_session_expiry
            # Remove any custom expiration for this session.
            try:
                del self['_session_expiry']
            except KeyError:
                pass
            return
        if isinstance(value, timedelta):
            value = timezone.now() + value
        self['_session_expiry'] = value                                             # 否则设置当前过期时间为该值

    def get_expire_at_browser_close(self):
        """
        Returns ``True`` if the session is set to expire when the browser
        closes, and ``False`` if there's an expiry date. Use
        ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry
        date/age, if there is one.
        """
        if self.get('_session_expiry') is None:                                     # 如果_session_expiry会话过期时间没有设置
            return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE                         # 则返回配置文件中是否浏览器关闭会话结束参数
        return self.get('_session_expiry') == 0                                     # 判断会话过期时间是否为0,如果为0就在浏览器关闭会话过期

    def flush(self):
        """
        Removes the current session data from the database and regenerates the
        key.
        """
        self.clear()                                                                # 清除会话数据
        self.delete()
        self._session_key = None                                                    # 将当前会话置空

    def cycle_key(self):
        """
        Creates a new session key, while retaining the current session data.
        """
        data = self._session_cache                                                  # 获取当前会话保存的数据
        key = self.session_key                                                      # 获取当前的key
        self.create()                                                               # 重新生成key
        self._session_cache = data                                                  # 将会话数据重新保存
        if key:
            self.delete(key)                                                        # 删除旧key对应的数据

    # Methods that child classes must implement.

    def exists(self, session_key):
        """
        Returns True if the given session_key already exists.
        """
        raise NotImplementedError('subclasses of SessionBase must provide an exists() method')

    def create(self):
        """
        Creates a new session instance. Guaranteed to create a new object with
        a unique key and will have saved the result once (with empty data)
        before the method returns.
        """
        raise NotImplementedError('subclasses of SessionBase must provide a create() method')

    def save(self, must_create=False):
        """
        Saves the session data. If 'must_create' is True, a new session object
        is created (otherwise a CreateError exception is raised). Otherwise,
        save() only updates an existing object and does not create one
        (an UpdateError is raised).
        """
        raise NotImplementedError('subclasses of SessionBase must provide a save() method')

    def delete(self, session_key=None):
        """
        Deletes the session data under this key. If the key is None, the
        current session key value is used.
        """
        raise NotImplementedError('subclasses of SessionBase must provide a delete() method')

    def load(self):
        """
        Loads the session data and returns a dictionary.
        """
        raise NotImplementedError('subclasses of SessionBase must provide a load() method')

    @classmethod
    def clear_expired(cls):
        """
        Remove expired sessions from the session store.

        If this operation isn't possible on a given backend, it should raise
        NotImplementedError. If it isn't necessary, because the backend has
        a built-in expiration mechanism, it should be a no-op.
        """
        raise NotImplementedError('This backend does not support clear_expired().')

该基类主要是提供了获取session_key,加密和解密会话的值,计算会话过期的时间,设置会话过期的时间,删除会话数据等基本功能。
1.db存储会话数据
代码位于django.contrib.sessions.backends.db.py

class SessionStore(SessionBase):
    """
    Implements database session store.
    """
    def __init__(self, session_key=None):
        super(SessionStore, self).__init__(session_key)

    @classmethod
    def get_model_class(cls):
        # Avoids a circular import and allows importing SessionStore when
        # django.contrib.sessions is not in INSTALLED_APPS.
        from django.contrib.sessions.models import Session
        return Session

    @cached_property
    def model(self):
        return self.get_model_class()

    def load(self):
        try:
            s = self.model.objects.get(
                session_key=self.session_key,
                expire_date__gt=timezone.now()
            )                                                               # 从数据库中查找该key,并且过期时间大于当前时间的记录
            return self.decode(s.session_data)                              # 将查询到的数据进行解码返回
        except (self.model.DoesNotExist, SuspiciousOperation) as e:
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                logger.warning(force_text(e))
            self._session_key = None
            return {}                                                       # 如果没有查询到就返回为空

    def exists(self, session_key):
        return self.model.objects.filter(session_key=session_key).exists()  # 检查当前的key是否已经存在

    def create(self):
        while True:
            self._session_key = self._get_new_session_key()                 # 创建一个新的key值
            try:
                # Save immediately to ensure we have a unique entry in the
                # database.
                self.save(must_create=True)                                 # 保存该值
            except CreateError:
                # Key wasn't unique. Try again.
                continue
            self.modified = True
            return

    def create_model_instance(self, data):
        """
        Return a new instance of the session model object, which represents the
        current session state. Intended to be used for saving the session data
        to the database.
        """
        return self.model(
            session_key=self._get_or_create_session_key(),                  # 获取或者创建一个session_key
            session_data=self.encode(data),                                 # 根据给定的格式进行编码
            expire_date=self.get_expiry_date(),                             # 获取过期的时间
        )                                                                   # 生成一个实例,

    def save(self, must_create=False):
        """
        Saves the current session data to the database. If 'must_create' is
        True, a database error will be raised if the saving operation doesn't
        create a *new* entry (as opposed to possibly updating an existing
        entry).
        """
        if self.session_key is None:                                        # 检查key是否为空,为空则继续创建该值     
            return self.create()
        data = self._get_session(no_load=must_create)                       # 获取session的数据内容
        obj = self.create_model_instance(data)                              # 创建一个model实例
        using = router.db_for_write(self.model, instance=obj)               # 
        try:
            with transaction.atomic(using=using):                           # 开启事务
                obj.save(force_insert=must_create, force_update=not must_create, using=using)       # 保存该数据
        except IntegrityError:
            if must_create:
                raise CreateError
            raise
        except DatabaseError:
            if not must_create:
                raise UpdateError
            raise

    def delete(self, session_key=None):
        if session_key is None:
            if self.session_key is None:
                return
            session_key = self.session_key
        try:
            self.model.objects.get(session_key=session_key).delete()        # 删除该key对应的数据
        except self.model.DoesNotExist:
            pass

    @classmethod
    def clear_expired(cls):
        cls.get_model_class().objects.filter(expire_date__lt=timezone.now()).delete()  # 清除已经过期的数据

所有对数据的操作都是通过操作数据库来实现。

2.file存储会话数据
代码位于django.contrib.sessions.backends.file.py

class SessionStore(SessionBase):
    """
    Implements a file based session store.
    """
    def __init__(self, session_key=None):
        self.storage_path = type(self)._get_storage_path()                              # 获取存储路径
        self.file_prefix = settings.SESSION_COOKIE_NAME                                 # 获取cookie存储名称
        super(SessionStore, self).__init__(session_key)

    @classmethod
    def _get_storage_path(cls):
        try:
            return cls._storage_path                                                    # 获取类设置的存储路径属性值
        except AttributeError: 
            storage_path = getattr(settings, "SESSION_FILE_PATH", None)                 # 获取配置文件中的会话文件保存路径
            if not storage_path:
                storage_path = tempfile.gettempdir()                                    # 如果配置文件中没有配置,则直接创建一个临时文件夹

            # Make sure the storage path is valid.
            if not os.path.isdir(storage_path):                                         # 检查该文件夹的路径是否合法
                raise ImproperlyConfigured(
                    "The session storage path %r doesn't exist. Please set your"
                    " SESSION_FILE_PATH setting to an existing directory in which"
                    " Django can store session data." % storage_path)

            cls._storage_path = storage_path                                            # 给该类设置配置文件的路径
            return storage_path                                                         # 返回配置的文件路径

    def _key_to_file(self, session_key=None):
        """
        Get the file associated with this session key.
        """
        if session_key is None:
            session_key = self._get_or_create_session_key()                             # 获取session_key

        # Make sure we're not vulnerable to directory traversal. Session keys
        # should always be md5s, so they should never contain directory
        # components.
        if not set(session_key).issubset(set(VALID_KEY_CHARS)):                         # 检查生成的key值是否包含不合法的字母
            raise InvalidSessionKey(
                "Invalid characters in session key")

        return os.path.join(self.storage_path, self.file_prefix + session_key)          # 返回session会话的文件路径

    def _last_modification(self):
        """
        Return the modification time of the file storing the session's content.
        """
        modification = os.stat(self._key_to_file()).st_mtime                            # 获取session文件的最后文件修改时间
        if settings.USE_TZ:                                                             # 根据配置文件序列化修改时间
            modification = datetime.datetime.utcfromtimestamp(modification)
            modification = modification.replace(tzinfo=timezone.utc)
        else:
            modification = datetime.datetime.fromtimestamp(modification)
        return modification

    def _expiry_date(self, session_data):
        """
        Return the expiry time of the file storing the session's content.
        """
        expiry = session_data.get('_session_expiry')                                    # 获取过期时间,如果没有设置则默认为最后修改时间加上配置的会话时间
        if not expiry:
            expiry = self._last_modification() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)
        return expiry

    def load(self):     
        session_data = {}
        try:
            with open(self._key_to_file(), "rb") as session_file:                       # 读取存储在session文件中保存的数据
                file_data = session_file.read()
            # Don't fail if there is no data in the session file.
            # We may have opened the empty placeholder file.
            if file_data:                                                               # 如果读取到值
                try: 
                    session_data = self.decode(file_data)                               # 解析读取的数据值
                except (EOFError, SuspiciousOperation) as e:
                    if isinstance(e, SuspiciousOperation):
                        logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                        logger.warning(force_text(e))
                    self.create()                                                       # 如果解析出现错误则重新创建

                # Remove expired sessions.
                expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data))    # 计算还剩多久会话过期
                if expiry_age <= 0:                                                     # 如果会话过期则删除该会话删除后重新创建
                    session_data = {}
                    self.delete()
                    self.create()
        except (IOError, SuspiciousOperation):
            self._session_key = None
        return session_data                                                             # 返回会话数据

    def create(self):
        while True: 
            self._session_key = self._get_new_session_key()                             # 创建session_key直到保存成功为止
            try: 
                self.save(must_create=True)
            except CreateError:
                continue
            self.modified = True
            return

    def save(self, must_create=False):
        if self.session_key is None:
            return self.create()
        # Get the session data now, before we start messing
        # with the file it is stored within.
        session_data = self._get_session(no_load=must_create)                           # 获取会话数据

        session_file_name = self._key_to_file()                                         # 获取会话文件名称

        try:
            # Make sure the file exists.  If it does not already exist, an
            # empty placeholder file is created.
            flags = os.O_WRONLY | getattr(os, 'O_BINARY', 0)                            # 已只读,可能二进制的方式打开文件
            if must_create:
                flags |= os.O_EXCL | os.O_CREAT                                         # 如果文件已经创建则报错,创建并打开新文件
            fd = os.open(session_file_name, flags)                       
            os.close(fd)

        except OSError as e:
            if must_create and e.errno == errno.EEXIST:
                raise CreateError
            if not must_create and e.errno == errno.ENOENT:
                raise UpdateError
            raise

        # Write the session file without interfering with other threads
        # or processes.  By writing to an atomically generated temporary
        # file and then using the atomic os.rename() to make the complete
        # file visible, we avoid having to lock the session file, while
        # still maintaining its integrity.
        #
        # Note: Locking the session file was explored, but rejected in part
        # because in order to be atomic and cross-platform, it required a
        # long-lived lock file for each session, doubling the number of
        # files in the session storage directory at any given time.  This
        # rename solution is cleaner and avoids any additional overhead
        # when reading the session data, which is the more common case
        # unless SESSION_SAVE_EVERY_REQUEST = True.
        #
        # See ticket #8616.
        dir, prefix = os.path.split(session_file_name)                                      # 分解文件路径

        try:
            output_file_fd, output_file_name = tempfile.mkstemp(dir=dir, prefix=prefix + '_out_')   # 创建一个零食文件
            renamed = False
            try:
                try:
                    os.write(output_file_fd, self.encode(session_data).encode())            # 将会话数据写入文件
                finally: 
                    os.close(output_file_fd)                                                # 写入完成后关闭文件

                # This will atomically rename the file (os.rename) if the OS
                # supports it. Otherwise this will result in a shutil.copy2
                # and os.unlink (for example on Windows). See #9084.
                shutil.move(output_file_name, session_file_name)                            # 将临时文件重命名为session_file_name
                renamed = True
            finally:
                if not renamed:                                                             # 如果没有重命名
                    os.unlink(output_file_name)                                             # 将关掉链接到输出文件的文件

        except (OSError, IOError, EOFError):
            pass

    def exists(self, session_key):
        return os.path.exists(self._key_to_file(session_key))                               # 检查对应会话值得会话文件是否存在

    def delete(self, session_key=None):
        if session_key is None:
            if self.session_key is None:
                return
            session_key = self.session_key
        try:
            os.unlink(self._key_to_file(session_key))                                       # 关闭对应文件的连接
        except OSError:
            pass

    def clean(self):
        pass

    @classmethod
    def clear_expired(cls):
        storage_path = cls._get_storage_path()                                              # 获取存储文件的路径
        file_prefix = settings.SESSION_COOKIE_NAME                                          # 获取文件开头名称

        for session_file in os.listdir(storage_path):                                       # 遍历会话文件存放文件夹下的会话文件
            if not session_file.startswith(file_prefix):                                    # 如果不是以会话文件开头的文件则跳过
                continue
            session_key = session_file[len(file_prefix):]                                   # 获取会话的值
            session = cls(session_key)                                                      # 实例化该会话值对象
            # When an expired session is loaded, its file is removed, and a
            # new file is immediately created. Prevent this by disabling
            # the create() method.
            session.create = lambda: None                                                   # 重写该实例的create对象
            session.load()       

主要是通过操作文件,将会话数据加密后通过存储到文件中,主要检查会话文件是否存在来判断该会话是否存在。
3.cache存储会话数据
代码位于django.contrib.sessions.backends.cache.py

class SessionStore(SessionBase):
    """
    A cache-based session store.
    """
    cache_key_prefix = KEY_PREFIX

    def __init__(self, session_key=None):
        self._cache = caches[settings.SESSION_CACHE_ALIAS]                          # 获取配置文件中配置的缓存
        super(SessionStore, self).__init__(session_key)

    @property
    def cache_key(self):
        return self.cache_key_prefix + self._get_or_create_session_key()            # 添加key前缀

    def load(self):
        try:
            session_data = self._cache.get(self.cache_key)                          # 先获取缓存中是否有该值,没有返回空
        except Exception:
            # Some backends (e.g. memcache) raise an exception on invalid
            # cache keys. If this happens, reset the session. See #17810.
            session_data = None
        if session_data is not None:
            return session_data
        self._session_key = None
        return {}

    def create(self):
        # Because a cache can fail silently (e.g. memcache), we don't know if
        # we are failing to create a new session because of a key collision or
        # because the cache is missing. So we try for a (large) number of times
        # and then raise an exception. That's the risk you shoulder if using
        # cache backing.
        for i in range(10000):                                                      # 循环一万次创建,根据注释提示缓存可能失败为静默不报错状态
            self._session_key = self._get_new_session_key()
            try:
                self.save(must_create=True)
            except CreateError:
                continue
            self.modified = True
            return
        raise RuntimeError(
            "Unable to create a new session key. "
            "It is likely that the cache is unavailable.")

    def save(self, must_create=False):
        if self.session_key is None:
            return self.create()
        if must_create:
            func = self._cache.add                                                  # 如果是新增则直接add
        elif self._cache.get(self.cache_key) is not None:                           # 如果不是新增,则先检查缓存值数据是否已经存在,如果存在就是set
            func = self._cache.set
        else:
            raise UpdateError
        result = func(self.cache_key,
                      self._get_session(no_load=must_create),
                      self.get_expiry_age())                                        # 设置key value 过期时间
        if must_create and not result:                                              # 如果是必须创建,但是创建之后没有返回成功值则直接报错
            raise CreateError

    def exists(self, session_key):
        return session_key and (self.cache_key_prefix + session_key) in self._cache     # 检查会话值,会话值对应的key是否在缓存中

    def delete(self, session_key=None):
        if session_key is None:                                                         # 检查session_key是否为空,为空直接返回
            if self.session_key is None:
                return
            session_key = self.session_key
        self._cache.delete(self.cache_key_prefix + session_key)                         # 删除session_key对应的缓存数据

    @classmethod
    def clear_expired(cls):                                                             # 缓存自带过期删除功能不需要显式操作
        pass

利用缓存存储会话数据,效率较高,而且可以有比较成熟的内存缓存库的支持,建议使用该种类型的缓存。
至此,三种会话数据缓存的代码已经分析完毕,内容相对繁琐一点。

展开阅读全文

没有更多推荐了,返回首页