or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-flask-caching

Adds caching support to Flask applications.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/flask-caching@2.3.x

To install, run

npx @tessl/cli install tessl/pypi-flask-caching@2.3.0

0

# Flask-Caching

1

2

A Python library that adds comprehensive caching support to Flask web applications. Flask-Caching provides decorators for view and function caching, multiple cache backends (Redis, Memcached, filesystem, in-memory), and template fragment caching capabilities.

3

4

## Package Information

5

6

- **Package Name**: Flask-Caching

7

- **Language**: Python

8

- **Installation**: `pip install Flask-Caching`

9

10

## Core Imports

11

12

```python

13

from flask_caching import Cache

14

```

15

16

For specific functionality:

17

18

```python

19

from flask_caching import Cache, CachedResponse, make_template_fragment_key

20

```

21

22

## Basic Usage

23

24

```python

25

from flask import Flask

26

from flask_caching import Cache

27

28

app = Flask(__name__)

29

30

# Configure cache

31

app.config['CACHE_TYPE'] = 'SimpleCache' # In-memory cache

32

app.config['CACHE_DEFAULT_TIMEOUT'] = 300

33

34

# Initialize cache

35

cache = Cache(app)

36

37

# Use caching decorator on a view

38

@app.route('/expensive-operation')

39

@cache.cached(timeout=60)

40

def expensive_operation():

41

# Simulate expensive computation

42

result = perform_complex_calculation()

43

return f"Result: {result}"

44

45

# Use memoize decorator for functions with arguments

46

@cache.memoize(timeout=120)

47

def calculate_fibonacci(n):

48

if n <= 1:

49

return n

50

return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)

51

52

if __name__ == '__main__':

53

app.run()

54

```

55

56

## Architecture

57

58

Flask-Caching follows a modular architecture with clear separation of concerns:

59

60

- **Cache Class**: Central controller managing cache operations and configuration

61

- **Backend System**: Pluggable cache storage backends (Redis, Memcached, filesystem, etc.)

62

- **Decorator Layer**: Function and view decorators (@cached, @memoize) for transparent caching

63

- **Jinja2 Integration**: Template fragment caching through custom Jinja2 extension

64

- **Configuration Management**: Flask app configuration integration with sensible defaults

65

66

This design enables flexible caching strategies, from simple in-memory caching for development to distributed Redis clusters for production, while maintaining a consistent API across all backends.

67

68

## Capabilities

69

70

### Core Cache Operations

71

72

Direct cache manipulation methods for storing, retrieving, and managing cached data. These operations form the foundation for all caching functionality and provide fine-grained control over cache behavior.

73

74

```python { .api }

75

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

76

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

77

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

78

def clear() -> bool: ...

79

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

80

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

81

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

82

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

83

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

84

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

85

def unlink(*keys) -> List[str]: ...

86

```

87

88

[Core Operations](./core-operations.md)

89

90

### Caching Decorators

91

92

Function and view decorators that provide transparent caching capabilities. The @cached decorator caches view results, while @memoize caches function results based on arguments.

93

94

```python { .api }

95

def cached(

96

timeout: Optional[int] = None,

97

key_prefix: str = "view/%s",

98

unless: Optional[Callable] = None,

99

forced_update: Optional[Callable] = None,

100

response_filter: Optional[Callable] = None,

101

query_string: bool = False,

102

hash_method: Callable = hashlib.md5,

103

cache_none: bool = False,

104

make_cache_key: Optional[Callable] = None,

105

source_check: Optional[bool] = None,

106

response_hit_indication: Optional[bool] = False

107

) -> Callable: ...

108

109

def memoize(

110

timeout: Optional[int] = None,

111

make_name: Optional[Callable] = None,

112

unless: Optional[Callable] = None,

113

forced_update: Optional[Callable] = None,

114

response_filter: Optional[Callable] = None,

115

hash_method: Callable = hashlib.md5,

116

cache_none: bool = False,

117

source_check: Optional[bool] = None,

118

args_to_ignore: Optional[Any] = None

119

) -> Callable: ...

120

```

121

122

[Decorators](./decorators.md)

123

124

### Cache Backends

125

126

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

127

128

```python { .api }

129

class SimpleCache(BaseCache): ...

130

class RedisCache(BaseCache): ...

131

class RedisClusterCache(BaseCache): ...

132

class RedisSentinelCache(BaseCache): ...

133

class MemcachedCache(BaseCache): ...

134

class FileSystemCache(BaseCache): ...

135

class NullCache(BaseCache): ...

136

class UWSGICache(BaseCache): ...

137

class GoogleCloudStorageCache(BaseCache): ...

138

```

139

140

[Backends](./backends.md)

141

142

### Template Fragment Caching

143

144

Jinja2 template integration for caching expensive template fragments. Provides template-level caching control with configurable cache keys and timeouts.

145

146

```python { .api }

147

def make_template_fragment_key(

148

fragment_name: str,

149

vary_on: Optional[List[str]] = None

150

) -> str: ...

151

```

152

153

Template syntax:

154

```jinja2

155

{% cache timeout key1[, key2, ...] %}

156

...template content...

157

{% endcache %}

158

```

159

160

[Template Caching](./template-caching.md)

161

162

## Types

163

164

```python { .api }

165

class Cache:

166

def __init__(

167

self,

168

app: Optional[Flask] = None,

169

with_jinja2_ext: bool = True,

170

config=None

171

) -> None: ...

172

173

def init_app(self, app: Flask, config=None) -> None: ...

174

175

@property

176

def cache(self) -> BaseCache: ...

177

"""Access to the underlying cache backend instance."""

178

179

class CachedResponse(Response):

180

timeout: Optional[int]

181

def __init__(self, response, timeout): ...

182

183

class BaseCache:

184

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

185

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

186

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

187

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

188

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

189

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

190

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

191

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

192

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

193

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

194

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

195

```

196

197

## Configuration

198

199

Flask-Caching supports extensive configuration options:

200

201

**General Options:**

202

- `CACHE_TYPE` - Backend type ('SimpleCache', 'RedisCache', 'filesystem', etc.)

203

- `CACHE_DEFAULT_TIMEOUT` - Default cache timeout in seconds (default: 300)

204

- `CACHE_KEY_PREFIX` - Prefix for all cache keys (default: 'flask_cache_')

205

- `CACHE_THRESHOLD` - Maximum cache items before cleanup (default: 500)

206

- `CACHE_IGNORE_ERRORS` - Whether to ignore cache backend errors (default: False)

207

- `CACHE_SOURCE_CHECK` - Include source code in cache keys (default: False)

208

- `CACHE_NO_NULL_WARNING` - Suppress null cache warnings (default: False)

209

- `CACHE_OPTIONS` - Additional cache options dictionary

210

- `CACHE_ARGS` - Additional cache arguments list

211

212

**Redis Options:**

213

- `CACHE_REDIS_HOST` - Redis server host (default: 'localhost')

214

- `CACHE_REDIS_PORT` - Redis server port (default: 6379)

215

- `CACHE_REDIS_DB` - Redis database number (default: 0)

216

- `CACHE_REDIS_PASSWORD` - Redis authentication password

217

- `CACHE_REDIS_URL` - Redis connection URL

218

- `CACHE_REDIS_SENTINELS` - Redis Sentinel servers list

219

- `CACHE_REDIS_SENTINEL_MASTER` - Redis Sentinel master name

220

- `CACHE_REDIS_SENTINEL_PASSWORD` - Redis Sentinel password

221

- `CACHE_REDIS_CLUSTER` - Redis Cluster connection string

222

223

**Memcached Options:**

224

- `CACHE_MEMCACHED_SERVERS` - List of Memcached servers

225

- `CACHE_MEMCACHED_USERNAME` - SASL username (for SASLMemcachedCache)

226

- `CACHE_MEMCACHED_PASSWORD` - SASL password (for SASLMemcachedCache)

227

228

**Filesystem Options:**

229

- `CACHE_DIR` - Directory for filesystem cache

230

231

**UWSGI Options:**

232

- `CACHE_UWSGI_NAME` - UWSGI cache name