本文整理汇总了Python中werkzeug.contrib.cache.FileSystemCache.set_many方法的典型用法代码示例。如果您正苦于以下问题:Python FileSystemCache.set_many方法的具体用法?Python FileSystemCache.set_many怎么用?Python FileSystemCache.set_many使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.contrib.cache.FileSystemCache
的用法示例。
在下文中一共展示了FileSystemCache.set_many方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from werkzeug.contrib.cache import FileSystemCache [as 别名]
# 或者: from werkzeug.contrib.cache.FileSystemCache import set_many [as 别名]
class CacheMiddleware:
def __init__(self, app, cache_dir='/tmp/cache', lock_file=None):
if not os.path.isdir(cache_dir):
os.mkdir(cache_dir)
self.app = app
self.cache = FileSystemCache(cache_dir, default_timeout=600)
self.t_local = threading.local()
if lock_file is not None:
lock_file = os.path.abspath(os.path.realpath(lock_file))
else:
lock_file = '/tmp/cache.lock'
self.lock_file = open(lock_file, 'wb+')
self.t_lock = threading.Lock()
def __call__(self, environ, start_response):
self.t_local.start_server_response = start_response
# get keys content, header and status
self.t_local.content_key = environ['PATH_INFO']
if environ.get('QUERY_STRING'):
self.t_local.content_key = '%s?%s' % (self.t_local.content_key,
environ['QUERY_STRING'])
self.t_local.header_key = '%s|%s' % (self.t_local.content_key, 'header')
self.t_local.status_key = '%s|%s' % (self.t_local.content_key, 'status')
# get cached response
keys = (self.t_local.content_key, self.t_local.header_key,
self.t_local.status_key)
with self.t_lock:
try:
fcntl.lockf(self.lock_file, fcntl.LOCK_SH)
content, headers, status = self.cache.get_many(*keys)
finally:
fcntl.lockf(self.lock_file, fcntl.LOCK_UN)
if (content is not None
and headers is not None
and status is not None):
# return cached response
self.t_local.start_server_response(status, headers)
return content
else:
# call app and cache the response
content = self.app(environ, self.start_response)
if self.do_cache():
content = list(content)
cached = {self.t_local.content_key: content,
self.t_local.header_key: self.t_local.headers,
self.t_local.status_key: self.t_local.status}
with self.t_lock:
try:
fcntl.lockf(self.lock_file, fcntl.LOCK_EX)
self.cache.set_many(cached)
finally:
fcntl.lockf(self.lock_file, fcntl.LOCK_UN)
return content
def start_response(self, status, response_headers, exc_info=None):
self.t_local.status = status
self.t_local.headers = response_headers
self.t_local.start_server_response(status, response_headers, exc_info)
def do_cache(self):
if 200 <= int(self.t_local.status.split(' ')[0]) < 300:
return True
else:
return False