本文整理汇总了Python中werkzeug.contrib.cache.SimpleCache.get方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleCache.get方法的具体用法?Python SimpleCache.get怎么用?Python SimpleCache.get使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.contrib.cache.SimpleCache
的用法示例。
在下文中一共展示了SimpleCache.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_simplecache_set_many
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
def test_simplecache_set_many():
"""Make sure set_many works with sequences as well as dicts"""
cache = SimpleCache()
cache.set_many({0: 0, 1: 1, 2: 4})
assert cache.get(2) == 4
cache.set_many((i, i*i) for i in xrange(3))
assert cache.get(2) == 4
示例2: HybridCache
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class HybridCache(object):
"""
A hybrid cache class that provide in-process cache that is backup up by out-of-process cache
When setting a key it will set it in both in-process and out-of-process
When getting a key it will try to retrieve first from in-process and if not, from out-of-process
"""
def __init__(self, remote_addresses):
self.in_proc_cache = SimpleCache(1000, 3600) #todo - pass these are arguments
self.remote_addresses = remote_addresses
self.out_proc_cache = MemcachedCache(remote_addresses)
def get(self, key):
"""
get an item from the hybrid cache
first in the in-process and then in the out-of-process
in case the key does not exist in both return None
if the value exist in out of process but not in-process then it is added
"""
val = self.in_proc_cache.get(key)
if val is None:
val = MemcachedCache(self.remote_addresses).get(key)
if val is not None:
self.in_proc_cache.add(key, val, None) #todo: for how long to cache?
return val
def add(self, key, value, timeout = 300):
"""
store a key-value in the hybrid cache - both in and out-off process
"""
#self.out_proc_cache.add(key, value, timeout = timeout)
MemcachedCache(self.remote_addresses).add(key, value, timeout)
self.in_proc_cache.add(key, value, timeout = timeout)
示例3: find
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
def find(self, query, index):
from flask import g
from werkzeug.contrib.cache import SimpleCache
cache = SimpleCache()
CACHE_TIMEOUT = 86400
index = cache.get('bokbok:metrics_index')
if not cache.get('bokbok:metrics_list'):
metrics_list = list(g.redis.smembers('bokbok:metrics_cache'))
cache.set('bokbok:metrics_list', metrics_list, CACHE_TIMEOUT)
if not index:
index = self.index(metrics_list)
cache.set('bokbok:metrics_index', index, CACHE_TIMEOUT)
return [metric for metric in sorted(index) if query in metric]
示例4: Metrics
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class Metrics(object):
def __init__(self):
self._cache = SimpleCache()
self._metrics = []
def build_keyspace(self, fields):
"""
Given: ["one", "two", "three"]
Yield: "one", "one.two", "one.two.three"
"""
current = set()
for field in fields:
current.add(field)
yield ".".join(current)
def index(self):
if not self._metrics:
r = requests.get("%s/metrics/index.json" % graphite_url)
self._metrics = json.loads(r.text)
def search(self, term):
cache_key = term
rv = self._cache.get(cache_key)
if not rv:
rv = [metric for metric in self._metrics if term in metric]
self._cache.set(cache_key, rv, timeout=86400)
return rv
示例5: ImageSimpleCache
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class ImageSimpleCache(ImageCache):
"""Simple image cache."""
def __init__(self):
"""Initialize the cache."""
super(ImageSimpleCache, self).__init__()
self.cache = SimpleCache()
def get(self, key):
"""Return the key value.
:param key: the object's key
:return: the stored object
:rtype: `BytesIO` object
"""
return self.cache.get(key)
def set(self, key, value, timeout=None):
"""Cache the object.
:param key: the object's key
:param value: the stored object
:type value: `BytesIO` object
:param timeout: the cache timeout in seconds
"""
timeout = timeout if timeout else self.timeout
self.cache.set(key, value, timeout)
def delete(self, key):
"""Delete the specific key."""
self.cache.delete(key)
def flush(self):
"""Flush the cache."""
self.cache.clear()
示例6: _UserSessions
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class _UserSessions(object):
def __init__(self):
self.cache = SimpleCache()
def create(self, user_id):
user = User.find(User.id == user_id)
if user is None:
return None
sess = os.urandom(24)
self.cache.set(sess, user_id)
session['key'] = sess
return sess
def get(self):
if 'key' not in session:
return None
key = session['key']
user_id = self.cache.get(key)
user = User.find(User.id == user_id)
session['user'] = user
return user
def delete(self):
if 'key' in session:
self.cache.delete(session['key'])
session.pop('key', None)
session.pop('user', None)
示例7: PostalBot
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class PostalBot(TelegramBot):
STR_USERNAME = 'USERNAME'
STR_MESSAGE_SENT = "Message sent"
SPAM_TIMEOUT = 10*60
def __init__(self, tg_api_key, tg_lounge_id):
super(PostalBot, self).__init__(tg_api_key, tg_lounge_id)
self.cache = SimpleCache()
def handle_stream_publish(self, data):
keys = data.keys()
if 'watch_url' in keys and 'username' in keys:
c_key = self.STR_USERNAME + ':' + data['username']
if not self.cache.get(c_key):
message = '{username} went live on Postal\n{url}'.format(
username=data['username'],
url=data['watch_url']
)
self.send_tg_message(self.tg_lounge_id, message)
self.cache.set(c_key, True, timeout=self.SPAM_TIMEOUT)
return self.STR_MESSAGE_SENT
return ''
def handle_postal_new_post(self, data):
keys = data.keys()
if 'username' in keys and 'title' in keys:
message = "New post by {username}\n{title}".format(
username=data['username'],
title=data['title']
)
if 'image_url' in keys and 'image_size' in keys:
message += "\n{url} {size}".format(
url=data['image_url'],
size=humanize.naturalsize(data['image_size'], gnu=True)
)
if 'file_url' in keys and 'file_size' in keys:
message += "\n{url} {size}".format(
url=data['file_url'],
size=humanize.naturalsize(data['file_size'], gnu=True)
)
self.send_tg_message(self.tg_lounge_id, message)
return self.STR_MESSAGE_SENT
return ''
def handle_tg_update(self, data):
keys = data.keys()
if 'message' in keys:
self.handle_tg_message(data['message'])
return ''
def handle_tg_message(self, message):
# print "%s %s: %s" % (message['from']['first_name'], message['from']['last_name'], message['text'])
pass
示例8: ZopeTemplateLoader
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class ZopeTemplateLoader(jinja2.BaseLoader):
def __init__(self, parent_loader, base_path,
cache_templates=True, template_list=[]):
self.parent_loader = parent_loader
self.cache = SimpleCache()
self.cache_templates = cache_templates
self.path = base_path
self.template_list = template_list
def get_source(self, environment, template):
def passthrough(cachable=True):
up = self.parent_loader
source, path, uptodate = up.get_source(environment, template)
if not cachable:
uptodate = lambda: False
return source, path, uptodate
if not template in self.template_list:
return passthrough()
path = "%s%s" % (self.path, template)
source = self.cache.get(path)
if not source:
try:
response = requests.get(path)
except requests.exceptions.ConnectionError:
return passthrough(cachable=False)
if response.status_code != 200:
return passthrough(cachable=False)
# escape jinja tags
source = response.text
source = source.strip()
source = source.replace("{%", "{{ '{%' }}").replace("%}", "{{ '%}' }}")
source = source.replace("{{", "{{ '{{' }}").replace("}}", "{{ '}}' }}")
# template blocks
source = source.replace("<!-- block_content -->",
"{% block natura2000_content %}{% endblock %}")
source = source.replace("<!-- block_head -->",
"{% block head %}{% endblock %}")
# fix breadcrumb link
source = source.replace('"%s"' % self.path,
'"%s"' % flask.url_for('naturasites.index'))
if self.cache_templates:
self.cache.set(path, source)
return source, path, lambda: False
示例9: Cache
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class Cache(object):
timeout = 604800 #week
cache = None
def __init__(self, timeout=None):
self.timeout = timeout or self.timeout
self.cache = SimpleCache()
def __call__(self, f):
@wraps(f)
def decorator(*args, **kwargs):
key = request.data + request.path
response = self.cache.get(key)
if response is None:
response = f(*args, **kwargs)
self.cache.set(key, response, self.timeout)
return response
return decorator
def get(self, key):
return self.cache.get(key)
def set(self, key, val):
return self.cache.set(key, val, self.timeout)
示例10: BGAPI
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class BGAPI(object):
# Timeout (in minutes)
cache_timeout = 1440
def __init__(self):
self.cache = SimpleCache()
with open(app.app.config["BG_API_KEY"], "r") as f:
self.auth_params = json.load(f)
def get(self, url_path, params={}):
"""Build a simple cache of the requested data"""
rv = self.cache.get(url_path)
if rv is None:
params.update(self.auth_params)
url = "https://api.biblegateway.com/3/" + url_path
response = requests.get(url, params=params)
if response.status_code != 200:
request = response.request
raise RuntimeError("{} request {} returned {}".format(request.method, request.url, response.status_code))
rv = response.json()
self.cache.set(url_path, rv, timeout=self.cache_timeout*60)
return rv
def list_translations(self):
return self.get('bible')['data']
def get_translation(self, xlation):
return self.get('bible/{}'.format(xlation))['data'][0]
def get_book_info(self, xlation, book_osis):
all_books = self.get_translation(xlation)['books']
for book in all_books:
if book['osis'] == book_osis:
return book
raise RuntimeError("Invalid book {} in translation {}".format(book_osis, xlation))
def get_passage(self, xlation, passage_osis):
verse_json = self.get("bible/{}/{}".format(passage_osis, xlation))['data'][0]
passage_json = verse_json['passages'][0]
return {'reference': passage_json['reference'],
'content': passage_json['content']}
示例11: get_status_for_user
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
def get_status_for_user():
cache = SimpleCache()
localization = cache.get("user_localization")
return jsonify(value=localization)
示例12: __init__
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class Server:
service_pages = [
'\/api\/ping(\?data=[0-9]+)?$',
'\/api\/getRequestPerSec$',
'\/api\/get_table\?(table=.+)$'
]
def __init__(self, ip, domain=None, seed=None):
self.ip = ip
self.domain = domain if domain != '' else None
self.app = Flask(__name__)
self.app.config['MAX_CONTENT_LENGTH'] = const.MAX_AVATAR_SIZE * 1024
self.sessions = dict()
self.sessions_by_user_name = dict()
for obj in DB.get_sessions():
s = Session(obj.name, obj.activated, obj.uid, obj.id, obj.admin)
self.sessions[obj.id] = s
self.sessions_by_user_name[obj.name] = s
self.rooms = {
'PvE': {0: RoomPvE()},
'PvP': {0: RoomPvP()},
'Friends': {0: RoomFriend()}
}
# TODO(debug): При релизе убрать этот костыль для подсветки типов :)
del self.rooms['PvE'][0]
del self.rooms['PvP'][0]
del self.rooms['Friends'][0]
self.logger = Logger()
self.logger.write_msg('==Server run at %s==' % ip)
self.seed = seed
self.cache = SimpleCache(default_timeout=60 * 60 * 24 * 30)
def update_status(this):
while True:
delta = timedelta(minutes=5)
now = datetime.now()
for s in this.sessions.values():
if not s.last_request or (s.last_request + delta < now and s.status == Session.ONLINE):
s.status = Session.OFFLINE
gevent.sleep(5 * 60 + 1)
gevent.spawn(update_status, self)
# Error handling
def error_handler_generator(e, data_):
def func1(e):
return render_template(
'error_page.html',
text=data_['text'],
description=data_['description']
), int(error)
func1.__name__ = "error" + e
return func1
http_errors = loads(open('server/configs/http_errors.json').read())
for error, data in http_errors.items():
self.app.error_handler_spec[None][int(error)] = error_handler_generator(error, data)
@self.app.route('/500') # static
def error_500_generator():
return None
# Error handling end
@self.app.after_request
def after_request(response):
session = self.get_session(request)
if session:
session['ip'] = request.remote_addr
session.last_request = datetime.now()
if session.status == Session.OFFLINE:
session.status = Session.ONLINE
if const.FILTRATE_REQUEST_FOR_LOG:
for item in self.service_pages:
if search(item, request.url):
break
else:
self.logger.write_record(request, response)
else:
self.logger.write_record(request, response)
return response
@self.app.route('/')
# static
def send_root():
session = self.get_session(request)
if session:
name = session.user
return render_template(
'main_menu.html', page_name='Дурак online', page_title='Главная',
user_name=name, admin=bool(session.admin))
elif session is None:
return redirect(self.app.config["APPLICATION_ROOT"] + '/static/login.html')
else:
session = self.sessions[request.cookies['sessID']]
session.update_activation_status()
return redirect(self.app.config["APPLICATION_ROOT"] + '/static/errors/not_activated.html')
#.........这里部分代码省略.........
示例13: SimpleCache
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
logger = logging.getLogger(__name__)
cache = SimpleCache()
# Provides a simple layer of caching for the video list, based on Memcached.
if "MEMCACHED" == CACHE_BACKEND:
# Try to use memcached
try:
cache = MemcachedCache([MEMCACHED_HOST_PORT])
# testing the connection
dummy_data = "The quick brown fox jumps over the lazy dog abcxyz"
cache.set("cs2015_dummy_data", dummy_data)
if dummy_data == cache.get("cs2015_dummy_data"):
logger.info("MemcachedCache was started successfully.")
else:
logger.info("MemcachedCache is not working correctly. Using SimpleCache.")
cache = SimpleCache()
except RuntimeError as e:
logger.warn("Error connecting to Memcached. Using SimpleCache. Error=[%r]." % e)
except:
logger.warn("Error connecting to Memcached. Error=[%r]." % sys.exc_info()[0])
'''
elif "REDIS" == CACHE_BACKEND:
# Try to use redis
try:
示例14: Exmail
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
class Exmail(object):
def __init__(self, app=None):
self.app = app
if app is not None:
self.init_app(app)
def init_app(self, app):
self._client_id = app.config['EXMAIL_ID']
self._client_secret = app.config['EXMAIL_SECRET']
self._cache_client = SimpleCache()
self.access_token_cache_url = 'exmail:access_token'
def _gen_access_token(self):
url = 'https://exmail.qq.com/cgi-bin/token'
payload = {
'client_id': self._client_id,
'client_secret': self._client_secret,
'grant_type': 'client_credentials',
}
r = requests.post(url, data=payload)
r_dict = r.json()
return (r_dict['access_token'], r_dict['expires_in'])
@property
def access_token(self):
access_token = self._cache_client.get(self.access_token_cache_url)
if not access_token:
access_token, expired_secs = self._gen_access_token()
self._cache_client.set(self.access_token_cache_url, access_token, expired_secs)
return access_token
def get_user(self, email):
url = 'http://openapi.exmail.qq.com:12211/openapi/user/get'
headers = { 'Authorization': 'Bearer %s' % self.access_token }
payload = {'alias': email}
r = requests.post(url=url, data=payload, headers=headers)
r_dict = r.json()
return r_dict
def update_user(self, email, update_dict):
print update_dict
url = 'http://openapi.exmail.qq.com:12211/openapi/user/sync'
update_dict['action'] = 3
update_dict['alias'] = email
# update_dict['md5'] = 0
headers = { 'Authorization': 'Bearer %s' % self.access_token }
r = requests.post(url=url, data=update_dict, headers=headers)
print r
return r
def update_password(self, email, password):
return self.update_user(email, {'password': password})
def add_user(self, email, name, password, org):
url = 'http://openapi.exmail.qq.com:12211/openapi/user/sync'
add_dict = {
'action': 2,
'alias': email,
'name': name,
'password': password,
'md5': 0,
'partypath': org,
'opentype': 1,
}
headers = { 'Authorization': 'Bearer %s' % self.access_token }
r = requests.post(url=url, data=add_dict, headers=headers)
print r.text
print r.status_code
def delete_user(self):
pass
示例15: int
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import get [as 别名]
brightness = int('0'+request.args['brightness']) if 'brightness' in request.args else None
if 'cam' in request.args:
cam = request.args['cam']
if re.match(ur'^/dev/video\d$', cam):
camera_id = cam
elif recently_used_cam == cam:
camera_id = recently_used_camera
else:
camera_id = get_camera_by_name(cam)
if camera_id is not None:
recently_used_cam = cam
recently_used_camera = camera_id
rotation=app.config['CAMERA_ROTATION'] if 'CAMERA_ROTATION' in app.config else None
cam_slug = "%s-%s-%s" % (camera_id, rotation, brightness)
filename = cache.get(cam_slug)
status = 200
if filename is None:
filename = os.path.join(app.config['TMP_IMAGES_PATH'], 'live-%s.jpeg' % (int(time.time()) % 10))
camera.get_webcam_image(filename, camera=camera_id, rotation=rotation, brightness=brightness)
cache.set(cam_slug, filename, timeout=2)
else:
status = 203
return send_file(filename if os.path.exists(filename) else 'static/gdoor.jpg', mimetype='image/jpeg'), status
@app.route('/action/gdoor')
def action_gdoor():
gpio.pulse(1)
# TODO: schedule door check here
return jsonify(**get_app_state())