or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

backends.mdexpiration.mdindex.mdmodels.mdpatching.mdserialization.mdsessions.md

patching.mddocs/

0

# Global Monkey-Patching

1

2

Global monkey-patching enables caching for all `requests` functions by replacing the standard `requests.Session` with a cached version. This approach requires no code changes and affects all requests made through the standard `requests` module functions.

3

4

**Warning**: These functions are not thread-safe. Use `CachedSession` for multi-threaded environments.

5

6

## Capabilities

7

8

### Installation and Management

9

10

Functions to globally install and manage caching for all requests functions.

11

12

```python { .api }

13

def install_cache(

14

cache_name: str = 'http_cache',

15

backend: Optional[BackendSpecifier] = None,

16

session_factory: Type[OriginalSession] = CachedSession,

17

**kwargs

18

):

19

"""

20

Install cache for all requests functions by monkey-patching requests.Session.

21

22

Parameters:

23

- cache_name: Cache path, prefix, or namespace

24

- backend: Backend name or instance

25

- session_factory: Session class to use (must inherit from CachedSession/CacheMixin)

26

- **kwargs: Additional arguments passed to session_factory

27

28

After installation, all requests.get(), requests.post(), etc. will use caching.

29

"""

30

31

def uninstall_cache():

32

"""

33

Disable caching by restoring original requests.Session.

34

"""

35

36

def get_cache() -> Optional[BaseCache]:

37

"""

38

Get the internal cache object from currently installed CachedSession.

39

40

Returns:

41

BaseCache instance if caching is installed, None otherwise

42

"""

43

44

def is_installed() -> bool:

45

"""

46

Check whether requests-cache is currently installed.

47

48

Returns:

49

True if monkey-patching is active, False otherwise

50

"""

51

```

52

53

#### Usage Examples

54

55

Basic installation:

56

57

```python

58

import requests_cache

59

import requests

60

61

# Install caching globally

62

requests_cache.install_cache('demo_cache')

63

64

# Now all requests functions use caching

65

response = requests.get('https://httpbin.org/get')

66

print(f"From cache: {response.from_cache}")

67

68

# Subsequent identical requests served from cache

69

response2 = requests.get('https://httpbin.org/get')

70

print(f"From cache: {response2.from_cache}") # True

71

72

# Remove caching

73

requests_cache.uninstall_cache()

74

```

75

76

Advanced configuration:

77

78

```python

79

import requests_cache

80

from datetime import timedelta

81

82

requests_cache.install_cache(

83

cache_name='advanced_cache',

84

backend='redis',

85

expire_after=timedelta(hours=1),

86

allowable_codes=[200, 404],

87

allowable_methods=['GET', 'POST'],

88

cache_control=True

89

)

90

91

# Check if caching is active

92

if requests_cache.is_installed():

93

cache = requests_cache.get_cache()

94

print(f"Cache contains {len(cache)} responses")

95

```

96

97

### Context Managers

98

99

Context managers for temporary caching control without affecting global state.

100

101

```python { .api }

102

def enabled(*args, **kwargs):

103

"""

104

Context manager for temporarily enabling caching.

105

106

Parameters:

107

- *args, **kwargs: Same as install_cache()

108

109

Usage:

110

with requests_cache.enabled('temp_cache'):

111

response = requests.get('https://example.com')

112

"""

113

114

def disabled():

115

"""

116

Context manager for temporarily disabling caching.

117

118

Usage:

119

with requests_cache.disabled():

120

response = requests.get('https://example.com') # Not cached

121

"""

122

```

123

124

#### Usage Examples

125

126

Temporary caching:

127

128

```python

129

import requests

130

import requests_cache

131

132

# Normal requests (no caching by default)

133

response1 = requests.get('https://httpbin.org/get')

134

135

# Temporarily enable caching

136

with requests_cache.enabled('temp_cache', expire_after=300):

137

response2 = requests.get('https://httpbin.org/get') # Cached

138

response3 = requests.get('https://httpbin.org/get') # From cache

139

140

# Back to normal requests (no caching)

141

response4 = requests.get('https://httpbin.org/get')

142

```

143

144

Temporary disable:

145

146

```python

147

import requests

148

import requests_cache

149

150

# Install caching globally

151

requests_cache.install_cache('global_cache')

152

153

response1 = requests.get('https://httpbin.org/get') # Cached

154

155

# Temporarily disable caching

156

with requests_cache.disabled():

157

response2 = requests.get('https://httpbin.org/get') # Not cached

158

159

response3 = requests.get('https://httpbin.org/get') # Back to caching

160

```

161

162

### Cache Operations

163

164

Functions to manage cached data globally when caching is installed.

165

166

```python { .api }

167

def clear():

168

"""

169

Clear the currently installed cache.

170

171

Removes all cached responses if caching is installed.

172

No effect if caching is not installed.

173

"""

174

175

def delete(*args, **kwargs):

176

"""

177

Remove responses from cache according to conditions.

178

179

Parameters:

180

- Same as BaseCache.delete() method

181

182

Common usage:

183

- delete(urls=['https://example.com']) # Delete specific URLs

184

- delete(expired=True) # Delete expired responses only

185

"""

186

```

187

188

#### Usage Examples

189

190

Cache management:

191

192

```python

193

import requests

194

import requests_cache

195

196

requests_cache.install_cache('demo_cache')

197

198

# Make some requests

199

requests.get('https://httpbin.org/get')

200

requests.get('https://httpbin.org/json')

201

requests.get('https://httpbin.org/headers')

202

203

# Check cache status

204

cache = requests_cache.get_cache()

205

print(f"Cache contains {len(cache)} responses")

206

207

# Clear specific URLs

208

requests_cache.delete(urls=['https://httpbin.org/get'])

209

210

# Clear expired responses

211

requests_cache.delete(expired=True)

212

213

# Clear all cached data

214

requests_cache.clear()

215

216

print(f"Cache now contains {len(requests_cache.get_cache())} responses")

217

```

218

219

## Integration with Existing Code

220

221

The monkey-patching approach is designed to work with existing codebases that use the standard `requests` library:

222

223

```python

224

# Existing code using requests

225

import requests

226

227

def fetch_api_data(url):

228

response = requests.get(url, headers={'Accept': 'application/json'})

229

return response.json()

230

231

def post_data(url, data):

232

return requests.post(url, json=data)

233

234

# Add caching with one line - no code changes needed

235

import requests_cache

236

requests_cache.install_cache('api_cache', expire_after=3600)

237

238

# Existing functions now use caching automatically

239

data = fetch_api_data('https://api.example.com/data')

240

result = post_data('https://api.example.com/submit', {'key': 'value'})

241

```

242

243

## Thread Safety Warning

244

245

Global monkey-patching functions are **not thread-safe**. In multi-threaded applications, use session-based caching instead:

246

247

```python

248

# Instead of this (not thread-safe):

249

requests_cache.install_cache('cache')

250

251

# Use this for multi-threaded apps:

252

from requests_cache import CachedSession

253

session = CachedSession('cache')

254

255

# Pass session to threads or use threading.local

256

import threading

257

thread_local = threading.local()

258

259

def get_session():

260

if not hasattr(thread_local, 'session'):

261

thread_local.session = CachedSession('thread_cache')

262

return thread_local.session

263

```

264

265

## Types

266

267

```python { .api }

268

# Session factory type for install_cache

269

Type[OriginalSession] = Type[requests.Session]

270

```