zoukankan      html  css  js  c++  java
  • 普通session vs MemcachedSession vs RedisSession

    一、普通session(数据存储在内存中)

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from hashlib import sha1
    import os
    import time
    import json
    
    create_session_id = lambda: sha1(bytes('%s%s' % (os.urandom(16), time.time()), encoding='utf-8')).hexdigest()
    class CacheSession: session_container = {} session_id = "__sessionId__" def __init__(self, handler): self.handler = handler client_random_str = handler.get_cookie(CacheSession.session_id, None) if client_random_str and client_random_str in CacheSession.session_container: self.random_str = client_random_str else: self.random_str = create_session_id() CacheSession.session_container[self.random_str] = {} expires_time = time.time() + config.SESSION_EXPIRES #超时时间 handler.set_cookie(CacheSession.session_id, self.random_str, expires=expires_time) def __getitem__(self, key): ret = CacheSession.session_container[self.random_str].get(key, None) return ret def __setitem__(self, key, value): CacheSession.session_container[self.random_str][key] = value def __delitem__(self, key): if key in CacheSession.session_container[self.random_str]: del CacheSession.session_container[self.random_str][key]

    二、将session存储在缓存(Memcache)中

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import config
    from hashlib import sha1
    import os
    import time
    import json
    import memcache
    conn = memcache.Client(['192.168.11.119:12000'], debug=True, cache_cas=True)
    create_session_id = lambda: sha1(bytes('%s%s' % (os.urandom(16), time.time()), encoding='utf-8')).hexdigest()
    
    class MemcachedSession:
        session_id = "__sessionId__"
    
        def __init__(self, handler):
            self.handler = handler
            # 从客户端获取随机字符串
            client_random_str = handler.get_cookie(MemcachedSession.session_id, None)
            # 如果从客户端获取到了随机字符串
            
            if client_random_str and conn.get(client_random_str):
                self.random_str = client_random_str
            else:
                self.random_str = create_session_id()
                conn.set(self.random_str, json.dumps({}), config.SESSION_EXPIRES) #config.SESSION_EXPIRES为匹配文件中设定的超时时间
    
            conn.set(self.random_str, conn.get(self.random_str), config.SESSION_EXPIRES)
    
            expires_time = time.time() + config.SESSION_EXPIRES
            handler.set_cookie(MemcachedSession.session_id, self.random_str, expires=expires_time)
    
        def __getitem__(self, key):
            ret = conn.get(self.random_str)
            ret_dict = json.loads(ret)
            result = ret_dict.get(key,None)
            return result
    
        def __setitem__(self, key, value):
            ret = conn.get(self.random_str)
            ret_dict = json.loads(ret)
            ret_dict[key] = value
            conn.set(self.random_str, json.dumps(ret_dict), config.SESSION_EXPIRES)
    
        def __delitem__(self, key):
            ret = conn.get(self.random_str)
            ret_dict = json.loads(ret)
            del ret_dict[key]
            conn.set(self.random_str, json.dumps(ret_dict), config.SESSION_EXPIRES)

    三、将session存储在缓存(Redis)中

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import config
    from hashlib import sha1
    import os
    import time
    import json
    import redis
    pool = redis.ConnectionPool(host='192.168.11.119', port=6379)
    r = redis.Redis(connection_pool=pool)
    
    create_session_id = lambda: sha1(bytes('%s%s' % (os.urandom(16), time.time()), encoding='utf-8')).hexdigest()
    
    class RedisSession:
        session_id = "__sessionId__"
    
        def __init__(self, handler):
            self.handler = handler
            # 从客户端获取随机字符串
            client_random_str = handler.get_cookie(RedisSession.session_id, None)
            # 如果从客户端获取到了随机字符串
            if client_random_str and r.exists(client_random_str):
                self.random_str = client_random_str
            else:
                self.random_str = create_session_id()
                r.hset(self.random_str,None,None)
    
            r.expire(self.random_str, config.SESSION_EXPIRES) #设置超时时间
    
    
            expires_time = time.time() + config.SESSION_EXPIRES
            handler.set_cookie(RedisSession.session_id, self.random_str, expires=expires_time)
    
        def __getitem__(self, key):
            result = r.hget(self.random_str,key)
            if result:
                ret_str = str(result, encoding='utf-8')
                try:
                    result = json.loads(ret_str)
                except:
                    result = ret_str
                return result
            else:
                return result
    
        def __setitem__(self, key, value):
            if type(value) == dict:
                r.hset(self.random_str, key, json.dumps(value))
            else:
                r.hset(self.random_str, key, value)
    
        def __delitem__(self, key):
            r.hdel(self.random_str,key)
    

  • 相关阅读:
    大数据和云计算如何实现视频行业更快速有效的智能分析?
    TSINGSEE青犀视频云边端架构流媒体平台的接口鉴权和接口保活是什么关系?
    TSINGSEE青犀视频和海康合作研发RTMP摄像头如何通过内存卡进行视频录像存储?
    RTMP视频推流功能组件EasyRTMP-HIK DEMO版本运行报错0xc000007b问题排查分析
    互联网视频直播&点播平台RTMP推流组件EasyRTMP如何获取当前推流状态 ?
    程序员修炼之道阅读笔记(一)
    周进度总结
    2020年秋季个人阅读计划
    周进度总结
    Java的Swing布局
  • 原文地址:https://www.cnblogs.com/luxiaojun/p/5790907.html
Copyright © 2011-2022 走看看