与sqlalchemy的缓存集成。
ecache的Python项目详细描述
运行测试
make unittest
安装/要求
pip intall ecache
用法
带烧瓶积分
fromflaskimportFlask,jsonifyfromflask_sqlalchemyimportSQLAlchemyfromecache.ext.flask_cacheimportCacheableMixin,query_callable,regionsapp=Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI']='sqlite:////tmp/test.db'app.debug=Truedb=SQLAlchemy(app)classUser(db.Model,CacheableMixin):"""Default backend is redis and expiration time is 1 hour, default region name is `default`, you can override this: cache_regions = your_regions cache_label = your_label """id=db.Column(db.Integer,primary_key=True)name=db.Column(db.String)@app.route('/users')defall_users():"""Result will try to get from cache first. load from db if cache miss. """users=[user.to_dict()foruserinUser.cache.filter()]returnjsonify(users=users)@app.route('/users/<int:user_id')defview_user(user_id):"""Result will try to get from cache first. load from db if cache miss. """user=User.cache.get(user_id)returnjsonify(user.to_dict())
更多详细信息请参见example
与纯sqlalchemy模型集成
# -*- coding: utf-8 -*-importredisfromsqlalchemyimport(Column,Integer,String,SmallInteger)fromecache.coreimportcache_mixinfromecache.dbimportdb_manager,model_base# alsosee :class:`ecache.db.DBManager`DBSession=db_manager.get_session('test')cache_client=redis.StrictRedis()CacheMixin=cache_mixin()DeclarativeBase=model_base()classTodoListModel(DeclarativeBase,CacheMixin):__tablename__=='todo_list'TABLE_CACHE_EXPIRATION_TIME=3600id=Column(Integer,primary_key=True)title=Column(String,default='')is_done=Column(SmallInteger,default=0)@classmethoddefget_todo(cls,todo_id):todo=cls.get(todo_id)# `cls.get` inherited from `CacheMixin`returntodo@classmethoddefadd(cls,title):todo=cls(title=title)s=DBSession()s.add(todo)s.commit()