2023年8月24日 15:30 by wst
web开发使用过flask中的session后,感觉还是挺方便的,能够保存用户的状态,又不用关心它是怎么实现的。
那么在sanic中是否有类似的机制呢?经过查找,发现了sanic_session.
安装方式:
pip install sanic_session
使用示例:
from sanic import Sanic
from sanic.response import text
from sanic_session import Session
app = Sanic()
Session(app)
@app.route("/")
async def index(request):
# interact with the session like a normal dict
if not request.ctx.session.get('foo'):
request.ctx.session['foo'] = 0
request.ctx.session['foo'] += 1
return text(str(request.ctx.session['foo']))
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)
现象:
每请求一次,得到的数字都会加1.
另外再安装依赖包:
pip install asyncio_redis
使用示例:
import asyncio_redis
from sanic import Sanic
from sanic.response import text
from sanic_session import Session, RedisSessionInterface
app = Sanic()
class Redis:
"""
A simple wrapper class that allows you to share a connection
pool across your application.
"""
_pool = None
async def get_redis_pool(self):
if not self._pool:
self._pool = await asyncio_redis.Pool.create(
host='localhost', port=6379, poolsize=10
)
return self._pool
redis = Redis()
Session(app, interface=RedisSessionInterface(redis.get_redis_pool))
@app.route("/")
async def test(request):
# interact with the session like a normal dict
if not request.ctx.session.get('foo'):
request.ctx.session['foo'] = 0
request.ctx.session['foo'] += 1
response = text(str(request.ctx.session['foo']))
return response
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)