or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

backends.mdcore-operations.mddecorators.mdindex.mdtemplate-caching.md

backends.mddocs/

0

# Cache Backends

1

2

Multiple cache storage backends for different deployment scenarios, from simple in-memory caching for development to distributed Redis clusters for production. Each backend implements the same interface while optimizing for specific use cases and infrastructure requirements.

3

4

## Capabilities

5

6

### Simple Cache Backend

7

8

In-memory cache for single-process development environments. Not thread-safe and data is lost on application restart.

9

10

```python { .api }

11

class SimpleCache(BaseCache):

12

"""

13

Simple memory cache for single process environments.

14

15

Parameters:

16

- threshold: Maximum number of items (default: 500)

17

- default_timeout: Default expiration time in seconds (default: 300)

18

- ignore_errors: Ignore errors during delete_many operations

19

"""

20

def __init__(

21

self,

22

threshold: int = 500,

23

default_timeout: int = 300,

24

ignore_errors: bool = False

25

): ...

26

```

27

28

**Configuration:**

29

```python

30

app.config['CACHE_TYPE'] = 'SimpleCache'

31

app.config['CACHE_THRESHOLD'] = 1000

32

app.config['CACHE_DEFAULT_TIMEOUT'] = 600

33

34

# Or use string backend name

35

app.config['CACHE_TYPE'] = 'simple'

36

```

37

38

### Redis Cache Backend

39

40

High-performance Redis-based cache with support for clustering and sentinel configurations.

41

42

```python { .api }

43

class RedisCache(BaseCache):

44

"""

45

Redis cache backend for scalable caching.

46

47

Parameters:

48

- host: Redis server host or Redis client instance

49

- port: Redis server port (default: 6379)

50

- password: Authentication password

51

- db: Database number (default: 0)

52

- default_timeout: Default expiration time in seconds

53

- key_prefix: Prefix for all cache keys

54

- **kwargs: Additional redis.Redis parameters

55

"""

56

def __init__(

57

self,

58

host: str = "localhost",

59

port: int = 6379,

60

password: Optional[str] = None,

61

db: int = 0,

62

default_timeout: int = 300,

63

key_prefix: Optional[str] = None,

64

**kwargs

65

): ...

66

67

class RedisClusterCache(BaseCache):

68

"""Redis Cluster cache backend for distributed caching."""

69

70

class RedisSentinelCache(BaseCache):

71

"""Redis Sentinel cache backend for high availability."""

72

```

73

74

**Configuration:**

75

```python

76

# Basic Redis configuration

77

app.config['CACHE_TYPE'] = 'RedisCache'

78

app.config['CACHE_REDIS_HOST'] = 'localhost'

79

app.config['CACHE_REDIS_PORT'] = 6379

80

app.config['CACHE_REDIS_DB'] = 0

81

app.config['CACHE_REDIS_PASSWORD'] = 'mypassword'

82

83

# Redis URL configuration

84

app.config['CACHE_TYPE'] = 'RedisCache'

85

app.config['CACHE_REDIS_URL'] = 'redis://localhost:6379/0'

86

87

# Redis Cluster

88

app.config['CACHE_TYPE'] = 'RedisClusterCache'

89

app.config['CACHE_REDIS_HOST'] = [

90

{'host': 'node1.redis.cluster', 'port': 6379},

91

{'host': 'node2.redis.cluster', 'port': 6379},

92

{'host': 'node3.redis.cluster', 'port': 6379}

93

]

94

95

# Or use string backend names

96

app.config['CACHE_TYPE'] = 'redis'

97

app.config['CACHE_TYPE'] = 'rediscluster'

98

app.config['CACHE_TYPE'] = 'redissentinel'

99

```

100

101

### Memcached Cache Backend

102

103

Memcached-based caching with support for multiple servers and SASL authentication.

104

105

```python { .api }

106

class MemcachedCache(BaseCache):

107

"""

108

Memcached cache backend.

109

110

Parameters:

111

- servers: List of memcached servers

112

- default_timeout: Default expiration time in seconds

113

- key_prefix: Prefix for all cache keys

114

"""

115

116

class SASLMemcachedCache(BaseCache):

117

"""Memcached cache with SASL authentication support."""

118

119

class SpreadSASLMemcachedCache(BaseCache):

120

"""Memcached cache with spread SASL authentication."""

121

```

122

123

**Configuration:**

124

```python

125

# Single Memcached server

126

app.config['CACHE_TYPE'] = 'MemcachedCache'

127

app.config['CACHE_MEMCACHED_SERVERS'] = ['127.0.0.1:11211']

128

129

# Multiple Memcached servers

130

app.config['CACHE_TYPE'] = 'MemcachedCache'

131

app.config['CACHE_MEMCACHED_SERVERS'] = [

132

'192.168.1.100:11211',

133

'192.168.1.101:11211',

134

'192.168.1.102:11211'

135

]

136

137

# SASL Authentication

138

app.config['CACHE_TYPE'] = 'SASLMemcachedCache'

139

app.config['CACHE_MEMCACHED_SERVERS'] = ['127.0.0.1:11211']

140

app.config['CACHE_MEMCACHED_USERNAME'] = 'myuser'

141

app.config['CACHE_MEMCACHED_PASSWORD'] = 'mypassword'

142

143

# Or use string backend names

144

app.config['CACHE_TYPE'] = 'memcached'

145

app.config['CACHE_TYPE'] = 'saslmemcached'

146

app.config['CACHE_TYPE'] = 'spreadsaslmemcached'

147

```

148

149

### Filesystem Cache Backend

150

151

File system-based cache that stores cached data as files on disk. Suitable for shared hosting environments or persistent caching needs.

152

153

```python { .api }

154

class FileSystemCache(BaseCache):

155

"""

156

File system cache backend.

157

158

Parameters:

159

- cache_dir: Directory path for cache files

160

- threshold: Maximum number of files (0 = no limit)

161

- default_timeout: Default expiration time in seconds

162

- mode: File permission mode (default: 0o600)

163

- hash_method: Hash function for filename generation

164

- ignore_errors: Ignore errors during delete_many operations

165

"""

166

def __init__(

167

self,

168

cache_dir: str,

169

threshold: int = 500,

170

default_timeout: int = 300,

171

mode: int = 0o600,

172

hash_method: Callable = hashlib.md5,

173

ignore_errors: bool = False

174

): ...

175

```

176

177

**Configuration:**

178

```python

179

app.config['CACHE_TYPE'] = 'FileSystemCache'

180

app.config['CACHE_DIR'] = '/var/cache/myapp'

181

app.config['CACHE_THRESHOLD'] = 1000

182

app.config['CACHE_DEFAULT_TIMEOUT'] = 300

183

184

# Or use string backend name

185

app.config['CACHE_TYPE'] = 'filesystem'

186

```

187

188

### Null Cache Backend

189

190

No-operation cache backend for testing and development. All cache operations succeed but nothing is actually cached.

191

192

```python { .api }

193

class NullCache(BaseCache):

194

"""

195

Null cache backend that performs no caching operations.

196

Useful for testing and development environments.

197

"""

198

```

199

200

**Configuration:**

201

```python

202

app.config['CACHE_TYPE'] = 'NullCache'

203

app.config['CACHE_NO_NULL_WARNING'] = True # Suppress warnings

204

205

# Or use string backend name

206

app.config['CACHE_TYPE'] = 'null'

207

```

208

209

### UWSGI Cache Backend

210

211

UWSGI-specific cache backend that leverages UWSGI's built-in caching capabilities.

212

213

```python { .api }

214

class UWSGICache(BaseCache):

215

"""

216

UWSGI cache backend using uwsgi.cache_* functions.

217

Only available when running under UWSGI server.

218

219

Parameters:

220

- default_timeout: Default expiration time in seconds (default: 300)

221

- cache: Name of the caching instance to connect to (default: "")

222

223

Note: This class cannot be used when running under PyPy.

224

Note: Requires cache2 to be enabled in uWSGI configuration.

225

"""

226

def __init__(self, default_timeout: int = 300, cache: str = ""): ...

227

```

228

229

**Configuration:**

230

```python

231

app.config['CACHE_TYPE'] = 'flask_caching.contrib.uwsgicache.UWSGICache'

232

app.config['CACHE_UWSGI_NAME'] = 'mycache'

233

234

# Legacy path (deprecated)

235

app.config['CACHE_TYPE'] = 'UWSGICache'

236

app.config['CACHE_UWSGI_NAME'] = 'mycache'

237

238

# Or use string backend name

239

app.config['CACHE_TYPE'] = 'uwsgi'

240

```

241

242

### Google Cloud Storage Cache Backend

243

244

Cloud-based cache backend using Google Cloud Storage buckets. User-contributed functionality for distributed caching in Google Cloud environments.

245

246

```python { .api }

247

class GoogleCloudStorageCache(BaseCache):

248

"""

249

Google Cloud Storage cache backend.

250

251

Parameters:

252

- bucket: GCS bucket name (must already exist)

253

- key_prefix: Prefix for all cache keys

254

- default_timeout: Default expiration time in seconds

255

- delete_expired_objects_on_read: Delete expired objects on read

256

- anonymous: Use anonymous credentials (for testing)

257

- **kwargs: Additional google.cloud.storage.Client parameters

258

"""

259

def __init__(

260

self,

261

bucket: str,

262

key_prefix: Optional[str] = None,

263

default_timeout: int = 300,

264

delete_expired_objects_on_read: bool = False,

265

anonymous: bool = False,

266

**kwargs

267

): ...

268

```

269

270

**Configuration:**

271

```python

272

app.config['CACHE_TYPE'] = 'flask_caching.contrib.GoogleCloudStorageCache'

273

app.config['CACHE_GCS_BUCKET'] = 'my-cache-bucket'

274

app.config['CACHE_GCS_KEY_PREFIX'] = 'myapp_cache_'

275

276

# Custom configuration

277

cache = Cache(app, config={

278

'CACHE_TYPE': 'flask_caching.contrib.GoogleCloudStorageCache',

279

'CACHE_GCS_BUCKET': 'my-cache-bucket',

280

'CACHE_GCS_DELETE_EXPIRED_ON_READ': True

281

})

282

```

283

284

### Base Cache Class

285

286

All cache backends inherit from BaseCache, which defines the common interface.

287

288

```python { .api }

289

class BaseCache:

290

"""

291

Base class for all cache backends.

292

293

Parameters:

294

- default_timeout: Default expiration time in seconds (default: 300)

295

"""

296

def __init__(self, default_timeout: int = 300): ...

297

298

@classmethod

299

def factory(cls, app, config, args, kwargs):

300

"""Factory method for creating cache instances."""

301

302

def get(self, key: str) -> Any: ...

303

def set(self, key: str, value: Any, timeout: Optional[int] = None) -> Optional[bool]: ...

304

def add(self, key: str, value: Any, timeout: Optional[int] = None) -> bool: ...

305

def delete(self, key: str) -> bool: ...

306

def delete_many(self, *keys) -> List[str]: ...

307

def has(self, key: str) -> bool: ...

308

def clear(self) -> bool: ...

309

def get_many(self, *keys) -> List[Any]: ...

310

def set_many(self, mapping: Dict[str, Any], timeout: Optional[int] = None) -> List[Any]: ...

311

def get_dict(self, *keys) -> Dict[str, Any]: ...

312

```

313

314

## Custom Backend Implementation

315

316

Create custom cache backends by inheriting from BaseCache:

317

318

```python

319

from flask_caching.backends.base import BaseCache

320

321

class MyCustomCache(BaseCache):

322

def __init__(self, custom_param=None, **kwargs):

323

super().__init__(**kwargs)

324

self.custom_param = custom_param

325

326

@classmethod

327

def factory(cls, app, config, args, kwargs):

328

kwargs.update({

329

'custom_param': config.get('CACHE_CUSTOM_PARAM')

330

})

331

return cls(*args, **kwargs)

332

333

def get(self, key):

334

# Custom get implementation

335

pass

336

337

def set(self, key, value, timeout=None):

338

# Custom set implementation

339

pass

340

341

# Implement other required methods...

342

343

# Register custom backend

344

app.config['CACHE_TYPE'] = 'myapp.cache.MyCustomCache'

345

```

346

347

## Backend Selection Guidelines

348

349

**Development:**

350

- `SimpleCache` - Quick setup, no external dependencies

351

- `NullCache` - Testing without caching side effects

352

353

**Production:**

354

- `RedisCache` - High performance, rich features, horizontal scaling

355

- `MemcachedCache` - Simple, fast, well-established

356

- `FileSystemCache` - Shared hosting, persistent cache across restarts

357

358

**High Availability:**

359

- `RedisClusterCache` - Distributed Redis setup

360

- `RedisSentinelCache` - Redis with automatic failover

361

- Multiple `MemcachedCache` servers with consistent hashing

362

363

**Specialized:**

364

- `UWSGICache` - When using UWSGI server with built-in caching

365

- Custom backends - Specific infrastructure requirements