跳转到主要内容

与SQLAlchemy的缓存集成。

项目描述

运行测试

make unittest

安装/要求

pip intall ecache

用法

与Flask集成

from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy

from ecache.ext.flask_cache import CacheableMixin, query_callable, regions

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.debug = True
db = SQLAlchemy(app)

class User(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')
def all_users():
    """Result will try to get from cache first. load from db if cache miss.
    """
    users = [user.to_dict() for user in User.cache.filter()]
    return jsonify(users=users)


@app.route('/users/<int:user_id')
def view_user(user_id):
    """Result will try to get from cache first. load from db if cache miss.
    """
    user = User.cache.get(user_id)
    return jsonify(user.to_dict())

更多详情请见示例

与纯SQLAlchemy模型集成

# -*- coding: utf-8 -*-

import redis
from sqlalchemy import (Column, Integer, String, SmallInteger)

from ecache.core import cache_mixin
from ecache.db import db_manager, model_base

# alsosee :class:`ecache.db.DBManager`
DBSession = db_manager.get_session('test')
cache_client = redis.StrictRedis()
CacheMixin = cache_mixin()
DeclarativeBase = model_base()


class TodoListModel(DeclarativeBase, CacheMixin):
    __tablename__ == 'todo_list'
    TABLE_CACHE_EXPIRATION_TIME = 3600

    id = Column(Integer, primary_key=True)
    title = Column(String, default='')
    is_done = Column(SmallInteger, default=0)

    @classmethod
    def get_todo(cls, todo_id):
        todo = cls.get(todo_id)  # `cls.get` inherited from `CacheMixin`
        return todo

    @classmethod
    def add(cls, title):
        todo = cls(title=title)
        s = DBSession()
        s.add(todo)
        s.commit()

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分布

ecache-0.1.2.tar.gz (11.9 kB 查看哈希值)

上传时间:

构建分布

ecache-0.1.2-py2-none-any.whl (16.7 kB 查看哈希值)

上传时间: Python 2