A bytecode cache that stores bytecode on the filesystem. It accepts two arguments: The directory where the cache items are stored and a pattern string that is used to build the filename. If no directory is specified the system temporary items folder is used. The pattern can be use
| 169 | |
| 170 | |
| 171 | class FileSystemBytecodeCache(BytecodeCache): |
| 172 | """A bytecode cache that stores bytecode on the filesystem. It accepts |
| 173 | two arguments: The directory where the cache items are stored and a |
| 174 | pattern string that is used to build the filename. |
| 175 | |
| 176 | If no directory is specified the system temporary items folder is used. |
| 177 | |
| 178 | The pattern can be used to have multiple separate caches operate on the |
| 179 | same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s`` |
| 180 | is replaced with the cache key. |
| 181 | |
| 182 | >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache') |
| 183 | |
| 184 | This bytecode cache supports clearing of the cache using the clear method. |
| 185 | """ |
| 186 | |
| 187 | def __init__(self, directory=None, pattern='__jinja2_%s.cache'): |
| 188 | if directory is None: |
| 189 | directory = tempfile.gettempdir() |
| 190 | self.directory = directory |
| 191 | self.pattern = pattern |
| 192 | |
| 193 | def _get_cache_filename(self, bucket): |
| 194 | return path.join(self.directory, self.pattern % bucket.key) |
| 195 | |
| 196 | def load_bytecode(self, bucket): |
| 197 | f = open_if_exists(self._get_cache_filename(bucket), 'rb') |
| 198 | if f is not None: |
| 199 | try: |
| 200 | bucket.load_bytecode(f) |
| 201 | finally: |
| 202 | f.close() |
| 203 | |
| 204 | def dump_bytecode(self, bucket): |
| 205 | f = open(self._get_cache_filename(bucket), 'wb') |
| 206 | try: |
| 207 | bucket.write_bytecode(f) |
| 208 | finally: |
| 209 | f.close() |
| 210 | |
| 211 | def clear(self): |
| 212 | # imported lazily here because google app-engine doesn't support |
| 213 | # write access on the file system and the function does not exist |
| 214 | # normally. |
| 215 | from os import remove |
| 216 | files = fnmatch.filter(listdir(self.directory), self.pattern % '*') |
| 217 | for filename in files: |
| 218 | try: |
| 219 | remove(path.join(self.directory, filename)) |
| 220 | except OSError: |
| 221 | pass |
| 222 | |
| 223 | |
| 224 | class MemcachedBytecodeCache(BytecodeCache): |