/usr/lib/python2.7/dist-packages/suds/cache.py is in python-suds 0.7~git20150727.94664dd-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | # This program is free software; you can redistribute it and/or modify it under
# the terms of the (LGPL) GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Library Lesser General Public License
# for more details at ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( jortel@redhat.com )
"""
Basic caching classes.
"""
import suds
import suds.sax.element
import suds.sax.parser
import datetime
import os
try:
import cPickle as pickle
except Exception:
import pickle
import shutil
import tempfile
from logging import getLogger
log = getLogger(__name__)
class Cache(object):
"""An object cache."""
def get(self, id):
"""
Get an object from the cache by id.
@param id: The object id.
@type id: str
@return: The object, else None.
@rtype: any
"""
raise Exception("not-implemented")
def put(self, id, object):
"""
Put an object into the cache.
@param id: The object id.
@type id: str
@param object: The object to add.
@type object: any
"""
raise Exception("not-implemented")
def purge(self, id):
"""
Purge an object from the cache by id.
@param id: A object id.
@type id: str
"""
raise Exception("not-implemented")
def clear(self):
"""Clear all objects from the cache."""
raise Exception("not-implemented")
class NoCache(Cache):
"""The pass-through object cache."""
def get(self, id):
return
def put(self, id, object):
pass
class FileCache(Cache):
"""
A file-based URL cache.
@cvar fnprefix: The file name prefix.
@type fnprefix: str
@cvar remove_default_location_on_exit: Whether to remove the default cache
location on process exit (default=True).
@type remove_default_location_on_exit: bool
@ivar duration: The duration after which cached entries expire (0=never).
@type duration: datetime.timedelta
@ivar location: The cached file folder.
@type location: str
"""
fnprefix = "suds"
__default_location = None
remove_default_location_on_exit = True
def __init__(self, location=None, **duration):
"""
Initialized a new FileCache instance.
If no cache location is specified, a temporary default location will be
used. Such default cache location will be shared by all FileCache
instances with no explicitly specified location within the same
process. The default cache location will be removed automatically on
process exit unless user sets the remove_default_location_on_exit
FileCache class attribute to False.
@param location: The cached file folder.
@type location: str
@param duration: The duration after which cached entries expire
(default: 0=never).
@type duration: keyword arguments for datetime.timedelta constructor
"""
if location is None:
location = self.__get_default_location()
self.location = location
self.duration = datetime.timedelta(**duration)
self.__check_version()
def clear(self):
for filename in os.listdir(self.location):
path = os.path.join(self.location, filename)
if os.path.isdir(path):
continue
if filename.startswith(self.fnprefix):
os.remove(path)
log.debug("deleted: %s", path)
def fnsuffix(self):
"""
Get the file name suffix.
@return: The suffix.
@rtype: str
"""
return "gcf"
def get(self, id):
try:
f = self._getf(id)
try:
return f.read()
finally:
f.close()
except Exception:
pass
def purge(self, id):
filename = self.__filename(id)
try:
os.remove(filename)
except Exception:
pass
def put(self, id, data):
try:
filename = self.__filename(id)
f = self.__open(filename, "wb")
try:
f.write(data)
finally:
f.close()
return data
except Exception:
log.debug(id, exc_info=1)
return data
def _getf(self, id):
"""Open a cached file with the given id for reading."""
try:
filename = self.__filename(id)
self.__remove_if_expired(filename)
return self.__open(filename, "rb")
except Exception:
pass
def __check_version(self):
path = os.path.join(self.location, "version")
try:
f = self.__open(path)
try:
version = f.read()
finally:
f.close()
if version != suds.__version__:
raise Exception()
except Exception:
self.clear()
f = self.__open(path, "w")
try:
f.write(suds.__version__)
finally:
f.close()
def __filename(self, id):
"""Return the cache file name for an entry with a given id."""
suffix = self.fnsuffix()
filename = "%s-%s.%s" % (self.fnprefix, id, suffix)
return os.path.join(self.location, filename)
@staticmethod
def __get_default_location():
"""
Returns the current process's default cache location folder.
The folder is determined lazily on first call.
"""
if not FileCache.__default_location:
tmp = tempfile.mkdtemp("suds-default-cache")
FileCache.__default_location = tmp
import atexit
atexit.register(FileCache.__remove_default_location)
return FileCache.__default_location
def __mktmp(self):
"""Create the I{location} folder if it does not already exist."""
try:
if not os.path.isdir(self.location):
os.makedirs(self.location)
except Exception:
log.debug(self.location, exc_info=1)
return self
def __open(self, filename, *args):
"""Open cache file making sure the I{location} folder is created."""
self.__mktmp()
return open(filename, *args)
@staticmethod
def __remove_default_location():
"""
Removes the default cache location folder.
This removal may be disabled by setting the
remove_default_location_on_exit FileCache class attribute to False.
"""
if FileCache.remove_default_location_on_exit:
# We must not load shutil here on-demand as under some
# circumstances this may cause the shutil.rmtree() operation to
# fail due to not having some internal module loaded. E.g. this
# happens if you run the project's test suite using the setup.py
# test command on Python 2.4.x.
shutil.rmtree(FileCache.__default_location, ignore_errors=True)
def __remove_if_expired(self, filename):
"""
Remove a cached file entry if it expired.
@param filename: The file name.
@type filename: str
"""
if not self.duration:
return
created = datetime.datetime.fromtimestamp(os.path.getctime(filename))
expired = created + self.duration
if expired < datetime.datetime.now():
os.remove(filename)
log.debug("%s expired, deleted", filename)
class DocumentCache(FileCache):
"""XML document file cache."""
def fnsuffix(self):
return "xml"
def get(self, id):
fp = None
try:
fp = self._getf(id)
if fp is None:
return None
p = suds.sax.parser.Parser()
return p.parse(fp)
except Exception:
if fp is not None:
fp.close()
self.purge(id)
def put(self, id, object):
if isinstance(object,
(suds.sax.document.Document, suds.sax.element.Element)):
super(DocumentCache, self).put(id, suds.byte_str(str(object)))
return object
class ObjectCache(FileCache):
"""
Pickled object file cache.
@cvar protocol: The pickling protocol.
@type protocol: int
"""
protocol = 2
def fnsuffix(self):
return "px"
def get(self, id):
fp = None
try:
fp = self._getf(id)
if fp is not None:
return pickle.load(fp)
except Exception:
if fp is not None:
fp.close()
self.purge(id)
def put(self, id, object):
data = pickle.dumps(object, self.protocol)
super(ObjectCache, self).put(id, data)
return object
|