當前位置: 首頁>>代碼示例>>Python>>正文


Python flask_cache.Cache類代碼示例

本文整理匯總了Python中flask_cache.Cache的典型用法代碼示例。如果您正苦於以下問題:Python Cache類的具體用法?Python Cache怎麽用?Python Cache使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Cache類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_sqla_cache

def test_sqla_cache(app, db, blueprint, request):
    cache = Cache(app)

    class OAuth(db.Model, OAuthConsumerMixin):
        pass

    blueprint.backend = SQLAlchemyBackend(OAuth, db.session, cache=cache)

    db.create_all()
    def done():
        db.session.remove()
        db.drop_all()
    request.addfinalizer(done)

    with record_queries(db.engine) as queries:
        with app.test_client() as client:
            # reset the session before the request
            with client.session_transaction() as sess:
                sess["test-service_oauth_state"] = "random-string"
            # make the request
            resp = client.get(
                "/login/test-service/authorized?code=secret-code&state=random-string",
                base_url="https://a.b.c",
            )
            # check that we redirected the client
            assert resp.status_code == 302
            assert resp.headers["Location"] == "https://a.b.c/oauth_done"

    assert len(queries) == 3

    expected_token = {
        "access_token": "foobar",
        "token_type": "bearer",
        "scope": [""],
    }

    # check the database
    authorizations = OAuth.query.all()
    assert len(authorizations) == 1
    oauth = authorizations[0]
    assert oauth.provider == "test-service"
    assert isinstance(oauth.token, dict)
    assert oauth.token == expected_token

    # cache should be invalidated
    assert cache.get("flask_dance_token|test-service|None") is None

    # first reference to the token should generate SQL queries
    with record_queries(db.engine) as queries:
        assert blueprint.token == expected_token
    assert len(queries) == 1

    # should now be in the cache
    assert cache.get("flask_dance_token|test-service|None") == expected_token

    # subsequent references should not generate SQL queries
    with record_queries(db.engine) as queries:
        assert blueprint.token == expected_token
    assert len(queries) == 0
開發者ID:Bachmann1234,項目名稱:flask-dance,代碼行數:59,代碼來源:test_sqla.py

示例2: test_21_redis_url_custom_db

 def test_21_redis_url_custom_db(self):
     config = {
         'CACHE_TYPE': 'redis',
         'CACHE_REDIS_URL': 'redis://localhost:6379/2',
     }
     cache = Cache()
     cache.init_app(self.app, config=config)
     rconn = self.app.extensions['cache'][cache] \
                 ._client.connection_pool.get_connection('foo')
     assert rconn.db == 2
開發者ID:mlenzen,項目名稱:flask-cache,代碼行數:10,代碼來源:test_cache.py

示例3: test_20_redis_url_default_db

 def test_20_redis_url_default_db(self):
     config = {
         'CACHE_TYPE': 'redis',
         'CACHE_REDIS_URL': 'redis://localhost:6379',
     }
     cache = Cache()
     cache.init_app(self.app, config=config)
     from werkzeug.contrib.cache import RedisCache
     assert isinstance(self.app.extensions['cache'][cache], RedisCache)
     rconn = self.app.extensions['cache'][cache] \
                 ._client.connection_pool.get_connection('foo')
     assert rconn.db == 0
開發者ID:mlenzen,項目名稱:flask-cache,代碼行數:12,代碼來源:test_cache.py

示例4: setUp

    def setUp(self):
        app = Flask(__name__, template_folder=os.path.dirname(__file__))

        app.debug = True
        self._set_app_config(app)

        self.cache = Cache(app)

        self.app = app
開發者ID:mlenzen,項目名稱:flask-cache,代碼行數:9,代碼來源:test_cache.py

示例5: test_06a_memoize

    def test_06a_memoize(self):
        self.app.config['CACHE_DEFAULT_TIMEOUT'] = 1
        self.cache = Cache(self.app)

        with self.app.test_request_context():
            @self.cache.memoize(50)
            def big_foo(a, b):
                return a+b+random.randrange(0, 100000)

            result = big_foo(5, 2)

            time.sleep(2)

            assert big_foo(5, 2) == result
開發者ID:mlenzen,項目名稱:flask-cache,代碼行數:14,代碼來源:test_cache.py

示例6: __init__

 def __init__(self, app=None, options=None, db=None):
     self._app = app
     self._db = db
     self.options = options
     if self.options is not None and 'conf_file' in self.options and self.options['conf_file'] is not None:
         logging_fileConfig(self.options['conf_file'])
     self._listener = None
     self._listener_lock = None
     self._sleep = 0.25
     self.menu_left = []
     # Bower
     self.bower = Bower()
     # Caching
     self.cache = Cache()
開發者ID:bibi21000,項目名稱:janitoo_flask,代碼行數:14,代碼來源:__init__.py

示例7: test_06b_memoize_func_only_special_args

    def test_06b_memoize_func_only_special_args(self):
        self.app.config['CACHE_DEFAULT_TIMEOUT'] = 1
        self.cache = Cache(self.app)

        with self.app.test_request_context():
            @self.cache.memoize(10)
            def big_foo(*args, **kwargs):
                return sum(args)

            res_1 = big_foo(1, 2, 3)

            time.sleep(1)

            res_2 = big_foo(4, 5, 6)

            assert res_1 != res_2
            assert res_1 == 6
            assert res_2 == 15
開發者ID:msmol,項目名稱:flask-cache,代碼行數:18,代碼來源:test_cache.py

示例8: test_19_dict_config_both

 def test_19_dict_config_both(self):
     cache = Cache(config={'CACHE_TYPE': 'null'})
     cache.init_app(self.app, config={'CACHE_TYPE': 'simple'})
     from werkzeug.contrib.cache import SimpleCache
     assert isinstance(self.app.extensions['cache'][cache], SimpleCache)
開發者ID:mlenzen,項目名稱:flask-cache,代碼行數:5,代碼來源:test_cache.py

示例9: test_17_dict_config

    def test_17_dict_config(self):
        cache = Cache(config={'CACHE_TYPE': 'simple'})
        cache.init_app(self.app)

        assert cache.config['CACHE_TYPE'] == 'simple'
開發者ID:mlenzen,項目名稱:flask-cache,代碼行數:5,代碼來源:test_cache.py

示例10: CacheTestCase

class CacheTestCase(unittest.TestCase):

    def _set_app_config(self, app):
        app.config['CACHE_TYPE'] = 'simple'

    def setUp(self):
        app = Flask(__name__, template_folder=os.path.dirname(__file__))

        app.debug = True
        self._set_app_config(app)

        self.cache = Cache(app)

        self.app = app

    def tearDown(self):
        self.app = None
        self.cache = None
        self.tc = None

    def test_00_set(self):
        self.cache.set('hi', 'hello')

        assert self.cache.get('hi') == 'hello'

    def test_01_add(self):
        self.cache.add('hi', 'hello')

        assert self.cache.get('hi') == 'hello'

        self.cache.add('hi', 'foobar')

        assert self.cache.get('hi') == 'hello'

    def test_02_delete(self):
        self.cache.set('hi', 'hello')

        self.cache.delete('hi')

        assert self.cache.get('hi') is None

    def test_03_cached_view(self):

        @self.app.route('/')
        @self.cache.cached(5)
        def cached_view():
            return str(time.time())

        tc = self.app.test_client()

        rv = tc.get('/')
        the_time = rv.data.decode('utf-8')

        time.sleep(2)

        rv = tc.get('/')

        assert the_time == rv.data.decode('utf-8')

        time.sleep(5)

        rv = tc.get('/')
        assert the_time != rv.data.decode('utf-8')

    def test_04_cached_view_unless(self):
        @self.app.route('/a')
        @self.cache.cached(5, unless=lambda: True)
        def non_cached_view():
            return str(time.time())

        @self.app.route('/b')
        @self.cache.cached(5, unless=lambda: False)
        def cached_view():
            return str(time.time())

        tc = self.app.test_client()

        rv = tc.get('/a')
        the_time = rv.data.decode('utf-8')

        time.sleep(1)

        rv = tc.get('/a')
        assert the_time != rv.data.decode('utf-8')

        rv = tc.get('/b')
        the_time = rv.data.decode('utf-8')

        time.sleep(1)
        rv = tc.get('/b')

        assert the_time == rv.data.decode('utf-8')

    def test_05_cached_function(self):

        with self.app.test_request_context():
            @self.cache.cached(2, key_prefix='MyBits')
            def get_random_bits():
                return [random.randrange(0, 2) for i in range(50)]

#.........這裏部分代碼省略.........
開發者ID:mlenzen,項目名稱:flask-cache,代碼行數:101,代碼來源:test_cache.py

示例11: register_cache

def register_cache(app):
    cache = Cache(config={'CACHE_TYPE': 'redis'})
    cache.init_app(app)
    return cache
開發者ID:Aoshee,項目名稱:maple-blog,代碼行數:4,代碼來源:clear_cache.py

示例12: test

def test(data):
    return data['message'].startswith('v2ex')


def handle(data, cache=None, **kwargs):
    message = data['message']
    ids = fetch(cache=cache, force=(True if u'刷新' in message else False))
    contents = []
    for id in ids:
        topic = cache.get(TOPIC_KEY.format(id))
        if not topic:
            continue
        node = topic['node']
        msg = u'<{0}|{1} [{2}]>   <{3}|{4}>'.format(TOPIC_URL.format(id),
                                                    cgi.escape(topic['title']),
                                                    topic['published'],
                                                    NODE_URL.format(node),
                                                    node)
        contents.append(msg)
    return '\n'.join(contents)


if __name__ == '__main__':
    from flask import Flask
    from flask_cache import Cache
    app = Flask(__name__)
    cache = Cache()
    cache.init_app(app, config={'CACHE_TYPE': 'simple'})
    with app.app_context():
        print handle({'message': 'v2ex'}, cache, app)
開發者ID:imlyj,項目名稱:slack_bot,代碼行數:30,代碼來源:v2ex.py

示例13: SSLify

from flask_cache import Cache
from flask_login import LoginManager
from flask_sslify import SSLify

from slot import app

# Set up logging
log = logging.getLogger('slot')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
log.addHandler(ch)

app.config.from_object('config')
sslify = SSLify(app, age=300)
cache = Cache(app, config={'CACHE_TYPE': 'redis'})

with app.app_context():
    cache.clear()

from slot.users.views import users_blueprint
from routes import dashboard, render_new_procedure_form, receive_sms, complete_procedure
import slot.users.controller as user_controller
import db_fieldbook as db
import error_mailer

error_mailer.initialize_app(app, additional_loggers=['slot'])

# Register blueprints
app.register_blueprint(users_blueprint)
開發者ID:nhshd-slot,項目名稱:slot,代碼行數:30,代碼來源:main.py

示例14: test_21_init_app_sets_app_attribute

 def test_21_init_app_sets_app_attribute(self):
     cache = Cache()
     cache.init_app(self.app)
     assert cache.app == self.app
開發者ID:sh4nks,項目名稱:flask-cache,代碼行數:4,代碼來源:test_cache.py

示例15: register_cache

def register_cache(app):
    cache = Cache()
    cache.init_app(app)
    return cache
開發者ID:HogwartsRico,項目名稱:maple-bbs,代碼行數:4,代碼來源:extensions.py


注:本文中的flask_cache.Cache類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。