python-Web-django-商城-session存入数据库

utils:

'''用户session'''

import datetime
from app01.models import Sessions

'''
iii = request.session.session_data
print(iii)

s = Session.objects.get(pk='lmefu9u5y6x5h2lumdrdq4xy0kma9dt3')
print(s.session_data)
print(s.get_decoded())
'''

from django.contrib.sessions.models import Session

class PersonSession():
    '''个人虚拟session'''
    def __init__(self,request):
        self.time = datetime.datetime.now()
        self.session = {}
        self._session = request.session.__dict__
        self.session_id = self._session['_SessionBase__session_key']
        self._s = Session.objects.get(pk=self.session_id)
        # 数据
        self.session_data = self._s.session_data
        self.session_time = self._s.expire_date
        self._page()

    @classmethod
    def get_session_store_class(cls):
        raise NotImplementedError

    # 获取dict格式session
    def get_decoded(self):
        session_store_class = self.get_session_store_class()
        return session_store_class().decode(self.session_data)


    def get_session(self,request):
        '''把数据存入request.session中'''

    def delete(self):
        ''''''
        session_obj = Sessions.objects.filter(session_id=self.session_id).delete()


    def save(self):
        '''session保存数据库'''
        if Sessions.objects.filter(session_id=self.session_id):
            pass
        else:
            session_obj = Sessions(session_id=self.session_id,session_data=self.session_data,session_time=self.session_time)
            session_obj.save()


    def _page(self):
        '''判断是否登陆,并赋值'''
        session_obj = Sessions.objects.filter(session_id=self.session_id).first()
        if session_obj:
            '''登陆了'''
            self.session_data = session_obj.session_data
            self._s.session_data = self.session_data
            self.session = self._s.get_decoded()
            return True
        return False

models:

# session
class Sessions(models.Model):
    '''request.session'''
    # 第二主键
    session_id = models.CharField(max_length=40, verbose_name='sessionID', null=False)
    session_data = models.TextField(verbose_name='数据', null=True)
    session_time = models.DateTimeField(max_length=11, verbose_name='存储有效期', null=False)

views:

request.session["memberName"] = member_obj.member_name
request.session["memberId"] = member_obj.id
from app01.utils.personSession import PersonSession
person = PersonSession(request)
person.save()

 

posted @ 2019-08-21 20:20  一觉昏睡人  阅读(454)  评论(0编辑  收藏  举报