本文整理汇总了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
示例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
示例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
示例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
示例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
示例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()
示例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
示例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)
示例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'
示例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)]
#.........这里部分代码省略.........
示例11: register_cache
def register_cache(app):
cache = Cache(config={'CACHE_TYPE': 'redis'})
cache.init_app(app)
return cache
示例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)
示例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)
示例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
示例15: register_cache
def register_cache(app):
cache = Cache()
cache.init_app(app)
return cache