PaferaPy Async 0.1
ASGI framework focused on simplicity and efficiency
Loading...
Searching...
No Matches
cache.py
Go to the documentation of this file.
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3
4import os
5import os.path
6import time
7
8# *********************************************************************
9class Cache(object):
10 """Simple filesystem cache implementation for storing binary objects.
11
12 Simply call cache.Store() to save the object and cache.Load() to
13 get the object back. path identifies the object while timeout
14 determines how long the object will be saved before timeout.
15 """
16
17 # -------------------------------------------------------------------
18 def __init__(self,
19 cachedir = 'cache',
20 timeout = 10,
21 keepcharacters = ['_']):
22 """Creates an instance of the cache.
23
24 keepcharacters is used to determine what non-alphanumeric characters
25 are allowed in the cache filename.
26 """
27
28 self.cachedir = cachedir
29 self.timeout = timeout
30 self.keepcharacters = keepcharacters
31
32 os.makedirs(self.cachedir, exist_ok = True)
33
34 # -------------------------------------------------------------------
35 def SanitizePath(self, path):
36 """Turns path from the application identifier into a name suitable
37 for the file system. It will accept all alphanumeric characters or
38 any characters in keepcharacters.
39 """
40
41 path = path.replace('/', '_')
42 return "".join(c for c in path if c.isalnum() or c in self.keepcharacters).rstrip()
43
44 # -------------------------------------------------------------------
45 def Load(self, path):
46 """Returns a binary object stored in the system, or an empty string
47 if the object has expired.
48
49 path is the identifier for the object wanted.
50 """
51
52 cachefile = os.path.join(self.cachedir, self.SanitizePath(path))
53
54 try:
55 stats = os.stat(cachefile)
56
57 if stats.st_mtime + self.timeout > time.time():
58 return open(cachefile, 'rb').read()
59 except Exception as e:
60 pass
61
62 return ''
63
64 # -------------------------------------------------------------------
65 def Store(self, path, data):
66 """Stores data as a binary object into the system.
67
68 path is the identifier for the object to be later retrieved.
69 """
70
71 cachefile = os.path.join(self.cachedir, self.SanitizePath(path))
72
73 with open(cachefile, 'wb') as f:
74 f.write(data)
75
Simple filesystem cache implementation for storing binary objects.
Definition: cache.py:9
def SanitizePath(self, path)
Turns path from the application identifier into a name suitable for the file system.
Definition: cache.py:35
def Store(self, path, data)
Stores data as a binary object into the system.
Definition: cache.py:65
def Load(self, path)
Returns a binary object stored in the system, or an empty string if the object has expired.
Definition: cache.py:45
def __init__(self, cachedir='cache', timeout=10, keepcharacters=['_'])
Creates an instance of the cache.
Definition: cache.py:21