webpy save session to redis

import redis
import web

SESSION = 'SESSION:'

class RedisStore(web.session.Store):

    """Store for saving a session in redis:
    import rediswebpy
    session = web.session.Session(app, rediswebpy.RedisStore(), initializer={'count': 0})
    """
    def __init__(self, ip='localhost', port=6379, db=0, initial_flush=False):
        self.redis_server = redis.Redis(ip, port, db)
        if initial_flush:
            """
            flushing the database is very important when you update your
            Session object initializer dictionary argument.
            E.g.
            # Before Update:
            session = web.session.Session(app,
                                          rediswebpy.RedisStore(initial_flush=True),
                                          initializer={'a':1})
            # After Update:
            session = web.session.Session(app,
                                          rediswebpy.RedisStore(initial_flush=True),
                                          initializer={'a':1, 'b':2})
            # This will cause an error if initial_flush=False since existing
            # sessions in Redis will not contain the key 'b'.
            """
            self.redis_server.flushdb()

    def __contains__(self, key):
        # test if session exists for given key
        return bool(self.redis_server.get(SESSION+key))

    def __getitem__(self, key):
        # attempt to get session data from redis store for given key
        data = self.redis_server.get(SESSION+key)
        # if the session existed for the given key
        if data:
            # update the expiration time
            self.redis_server.expire(SESSION+key,
                                     web.webapi.config.session_parameters.timeout)
            return self.decode(data)
        else:
            raise KeyError

    def __setitem__(self, key, value):
        # set the redis value for given key to the encoded value, and reset the
        # expiration time
        self.redis_server.set(SESSION+key,
                              self.encode(value))
        self.redis_server.expire(SESSION+key,
                                     web.webapi.config.session_parameters.timeout)

    def __delitem__(self, key):
        self.redis_server.delete(SESSION+key)

    def cleanup(self, timeout):
        # since redis takes care of expiration for us, we don't need to do any
        # clean up
        pass
import web
import memcache

class MemCacheStore(web.session.Store):
    mc = None
    def __init__(self):
        self.mc = memcache.Client(['127.0.0.1:11211'], debug=0)
    def __contains__(self, key):
        return self.mc.get(key) != None
    def __getitem__(self, key):
        return self.mc.get(key)
    def __setitem__(self, key, value):
        self.mc.set(key, value, time = web.config.session_parameters["timeout"])
    def __delitem__(self, key):
        self.mc.delete(key)
    def cleanup(self, timeout):
        pass # Not needed as we assigned the timeout to memcache

web.config.debug = False
urls = (
    "/count", "count",
    "/reset", "reset"
)

app = web.application(urls, locals())
session = web.session.Session(app, MemCacheStore(), initializer={'count': 0})

class count:
    def GET(self):
        session.count += 1
        return str(session.count)

class reset:
    def GET(self):
        session.kill()
        return ""

if __name__ == "__main__":
    app.run()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Session是Spring框架提供的一个应用程序级会话管理解决方案。它为应用程序提供了一种无状态的方式来管理用户会话。Spring Session提供了多种后端存储方式来存储用户会话信息,其中Redis是其中的一个存储后端。 Spring SessionRedis整合可以使得应用程序的会话信息存储在Redis中,从而可以实现分布式应用程序的会话管理。下面是Spring SessionRedis整合的步骤: 1. 添加Spring SessionRedis的依赖: ```xml <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session</artifactId> <version>2.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.2.2.RELEASE</version> </dependency> ``` 2. 配置Redis连接信息: ```java @Configuration @EnableRedisHttpSession public class RedisSessionConfig { @Bean public LettuceConnectionFactory connectionFactory() { return new LettuceConnectionFactory(new RedisStandaloneConfiguration("localhost", 6379)); } } ``` 3. 启用Spring Session: ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public HttpSessionIdResolver httpSessionIdResolver() { return HeaderHttpSessionIdResolver.xAuthToken(); } } ``` 4. 在需要使用Spring Session的Controller或Service中,注入HttpSession对象即可: ```java @RestController public class UserController { @GetMapping("/user") public String getUser(HttpSession session) { String userId = (String) session.getAttribute("userId"); return "User Id: " + userId; } @PostMapping("/user") public void createUser(HttpSession session, @RequestParam String userId) { session.setAttribute("userId", userId); } } ``` 通过以上步骤,就可以实现Spring SessionRedis的整合,从而实现分布式应用程序的会话管理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值