本文整理汇总了Python中werkzeug.contrib.cache.SimpleCache.set方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleCache.set方法的具体用法?Python SimpleCache.set怎么用?Python SimpleCache.set使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.contrib.cache.SimpleCache
的用法示例。
在下文中一共展示了SimpleCache.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Metrics
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [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
示例2: ImageSimpleCache
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [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()
示例3: _UserSessions
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [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)
示例4: PostalBot
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [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
示例5: test_simplecache_get_dict
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [as 别名]
def test_simplecache_get_dict():
"""SimpleCache.get_dict bug"""
cache = SimpleCache()
cache.set('a', 'a')
cache.set('b', 'b')
d = cache.get_dict('a', 'b')
assert 'a' in d
assert 'a' == d['a']
assert 'b' in d
assert 'b' == d['b']
示例6: UtilityTestCase
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [as 别名]
class UtilityTestCase(unittest.TestCase):
def setUp(self):
self.c = SimpleCache()
def test_werkzeug_cache_get_or_add_missing_key(self):
self.assertEquals('bar', werkzeug_cache_get_or_add(self.c, 'foo', 'bar', 10))
def test_werkzeug_cache_get_or_add_existing_key(self):
self.c.set('foo', 'bar')
self.assertEquals('bar', werkzeug_cache_get_or_add(self.c, 'foo', 'qux', 10))
示例7: ZopeTemplateLoader
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [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
示例8: find
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [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]
示例9: Word
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [as 别名]
class Word(object):
def __init__(self):
self.cache = SimpleCache(threshold=1000,
default_timeout=60*60)
def find_word(self, url):
""" if any of words in unused, then select one.
"""
def generator(url):
for l in [self.cache.get,
self.find_unused_word,
self.find_used_word]:
yield l(url)
for selected_word in generator(url):
if bool(selected_word):
self.cache.set(url, selected_word)
return selected_word
def find_url(self, word):
if exists_used_word_in_db(word):
return get_url_in_db(word)
return None
def find_unused_word(self, url):
# find one from unused
for word in split_words(url):
if exists_unused_word_in_db(word):
return select_unused_word_in_db(word, url)
# one random
last_word = choose_last_unused_word_in_db()
return select_unused_word_in_db(last_word, url)
def find_used_word(self, url):
words = {}
for word in split_words(url):
if exists_used_word_in_db(word):
words.setdefault(word,
get_last_modified_in_db(word))
oldest_word = ""
if bool(words):
oldest_word = min(words)
else:
oldest_word = choose_last_modified_used_word_in_db()
return select_used_word_in_db(oldest_word, url)
示例10: BGAPI
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [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: Cache
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [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)
示例12: SimpleCache
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [as 别名]
from flask import jsonify, request, send_file
import serial
cache = SimpleCache()
app = Flask(__name__)
ser = serial.Serial('/dev/ttyUSB0', 9600)
def send_value( value ):
char = str( chr( value ) )
ser.write( char )
def rgb_to_6bit( rgb ):
return int('00' + bin(int(rgb[0:1], 16))[2:].zfill(4)[0:2]
+ bin(int(rgb[2:3], 16))[2:].zfill(4)[0:2]
+ bin(int(rgb[4:5], 16))[2:].zfill(4)[0:2], 2)
@app.route('/color', methods=['GET', 'POST'])
def color():
if request.method == 'POST':
color = request.form['color']
cache.set('color', color)
send_value( rgb_to_6bit( color ) )
return jsonify( status = 'ok', color = color )
@app.route('/')
def index():
return send_file('templates/index.html')
if __name__ == '__main__':
cache.set('color', '000000')
app.run(host='0.0.0.0')
示例13: int
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [as 别名]
import os
import urllib
import requests
from flask import Flask, request
from werkzeug.contrib.cache import SimpleCache
port = int(os.environ['MOCK_SERVER_PORT'])
cache = SimpleCache()
cache.set('config', '{}')
cache.set('sgv', '[]')
app = Flask(__name__)
def _get_post_data(request):
return request.data or request.form.keys()[0]
@app.route('/auto-config', methods=['get'])
def auto_config():
"""Pebble config page which immediately returns config values.
Normally, the config page receives a return_to query parameter, to which it
must redirect using JavaScript, appending the user's preferences. When this
endpoint is requested by the Pebble SDK as if it were a config page, it
immediately GETs the return_to url, appending whatever preferences were set
in the cache by the most recent POST to /set-config.
"""
return_to = request.args.get('return_to')
requests.get(return_to + urllib.quote(cache.get('config')))
return ''
示例14: int
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [as 别名]
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--port')
parser.add_argument('--test-class')
args, _ = parser.parse_known_args()
port = int(args.port or os.environ.get('MOCK_SERVER_PORT') or 0)
if port == 0:
print "Port must be set via MOCK_SERVER_PORT or --port"
sys.exit()
COLLECTIONS = ['entries', 'treatments', 'profile', 'devicestatus']
cache = SimpleCache(default_timeout=999999)
for coll in COLLECTIONS:
cache.set(coll, '[]')
app = Flask(__name__)
def _get_post_json(request):
return json.loads(request.data or request.form.keys()[0])
@app.route('/api/v1/<coll>.json')
def get_collection(coll):
elements = _collection_from_test(coll, args.test_class) if args.test_class else _collection_from_cache(coll)
if coll == 'treatments':
return json.dumps(_filter_treatments(elements, request.args))
elif elements is not None:
return json.dumps(elements)
else:
raise NotFound
示例15: Exmail
# 需要导入模块: from werkzeug.contrib.cache import SimpleCache [as 别名]
# 或者: from werkzeug.contrib.cache.SimpleCache import set [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