0
# Cookie Handling
1
2
Cookie management functionality providing a dict-like interface for handling HTTP cookies with compatibility for both client and server-side cookie operations.
3
4
## Capabilities
5
6
### RequestsCookieJar Class
7
8
A CookieJar with dict-like interface that extends standard cookielib functionality.
9
10
```python { .api }
11
class RequestsCookieJar:
12
"""
13
Compatibility class for http.cookiejar.CookieJar with dict-like interface.
14
15
Provides convenient access to cookies while maintaining full CookieJar functionality.
16
"""
17
18
def __init__(self, policy=None):
19
"""
20
Initialize RequestsCookieJar.
21
22
Parameters:
23
- policy: CookiePolicy instance (optional)
24
"""
25
26
# Dict-like interface
27
def get(self, name: str, default=None, domain=None, path=None) -> str:
28
"""
29
Get cookie value by name.
30
31
Parameters:
32
- name: Cookie name
33
- default: Default value if cookie not found
34
- domain: Specific domain to search (optional)
35
- path: Specific path to search (optional)
36
37
Returns:
38
Cookie value or default
39
"""
40
41
def set(self, name: str, value: str, **kwargs):
42
"""
43
Set a cookie.
44
45
Parameters:
46
- name: Cookie name
47
- value: Cookie value
48
- **kwargs: Additional cookie attributes (domain, path, etc.)
49
50
Returns:
51
Cookie object
52
"""
53
54
def __getitem__(self, name: str) -> str:
55
"""Get cookie value by name."""
56
57
def __setitem__(self, name: str, value: str):
58
"""Set cookie value by name."""
59
60
def __delitem__(self, name: str):
61
"""Delete cookie by name."""
62
63
def __contains__(self, name: str) -> bool:
64
"""Check if cookie exists."""
65
66
def update(self, other):
67
"""Update cookies from another cookie jar or dict."""
68
69
def keys(self) -> list[str]:
70
"""Get list of cookie names."""
71
72
def values(self) -> list[str]:
73
"""Get list of cookie values."""
74
75
def items(self) -> list[tuple[str, str]]:
76
"""Get list of (name, value) tuples."""
77
78
def iterkeys(self):
79
"""Iterate over cookie names."""
80
81
def itervalues(self):
82
"""Iterate over cookie values."""
83
84
def iteritems(self):
85
"""Iterate over (name, value) tuples."""
86
87
# Cookie management methods
88
def list_domains(self) -> list[str]:
89
"""Get list of domains with cookies."""
90
91
def list_paths(self) -> list[str]:
92
"""Get list of paths with cookies."""
93
94
def multiple_domains(self) -> bool:
95
"""Check if cookies exist for multiple domains."""
96
97
def get_dict(self, domain=None, path=None) -> dict:
98
"""
99
Get cookies as a plain dict.
100
101
Parameters:
102
- domain: Filter by domain (optional)
103
- path: Filter by path (optional)
104
105
Returns:
106
Dict of cookie name -> value mappings
107
"""
108
109
def copy(self) -> 'RequestsCookieJar':
110
"""Create a copy of the cookie jar."""
111
112
def get_policy(self):
113
"""Get the cookie policy."""
114
```
115
116
### Cookie Utility Functions
117
118
Functions for cookie manipulation and conversion.
119
120
```python { .api }
121
def extract_cookies_to_jar(jar, request, response):
122
"""
123
Extract cookies from response and add to jar.
124
125
Parameters:
126
- jar: RequestsCookieJar to add cookies to
127
- request: Request object
128
- response: Response object
129
"""
130
131
def get_cookie_header(jar, request) -> str | None:
132
"""
133
Get Cookie header value from jar for request.
134
135
Parameters:
136
- jar: RequestsCookieJar containing cookies
137
- request: Request object
138
139
Returns:
140
Cookie header value or None
141
"""
142
143
def remove_cookie_by_name(cookiejar, name: str, domain=None, path=None):
144
"""
145
Remove cookie from jar by name.
146
147
Parameters:
148
- cookiejar: CookieJar to remove from
149
- name: Cookie name to remove
150
- domain: Domain filter (optional)
151
- path: Path filter (optional)
152
"""
153
154
def create_cookie(name: str, value: str, **kwargs):
155
"""
156
Create a Cookie object.
157
158
Parameters:
159
- name: Cookie name
160
- value: Cookie value
161
- **kwargs: Additional cookie attributes
162
163
Returns:
164
Cookie object
165
"""
166
167
def morsel_to_cookie(morsel):
168
"""
169
Convert http.cookies.Morsel to Cookie object.
170
171
Parameters:
172
- morsel: Morsel object to convert
173
174
Returns:
175
Cookie object
176
"""
177
178
def cookiejar_from_dict(cookie_dict: dict, cookiejar=None, overwrite=True):
179
"""
180
Create CookieJar from dictionary.
181
182
Parameters:
183
- cookie_dict: Dict of cookie name -> value mappings
184
- cookiejar: Existing jar to add to (optional)
185
- overwrite: Whether to overwrite existing cookies
186
187
Returns:
188
CookieJar containing the cookies
189
"""
190
191
def merge_cookies(cookiejar, cookies):
192
"""
193
Merge cookies into an existing jar.
194
195
Parameters:
196
- cookiejar: Target CookieJar
197
- cookies: Cookies to merge (dict or CookieJar)
198
199
Returns:
200
Updated CookieJar
201
"""
202
```
203
204
### Cookie Exceptions
205
206
```python { .api }
207
class CookieConflictError(RuntimeError):
208
"""Raised when multiple cookies match the same criteria."""
209
```
210
211
## Usage Examples
212
213
### Basic Cookie Operations
214
215
```python
216
import requests
217
218
# Cookies are automatically handled
219
response = requests.get('https://httpbin.org/cookies/set/sessionid/abc123')
220
print(response.cookies['sessionid']) # 'abc123'
221
222
# Access cookie jar
223
jar = response.cookies
224
print(jar.get('sessionid')) # 'abc123'
225
print('sessionid' in jar) # True
226
227
# Send cookies with request
228
cookies = {'user': 'john', 'token': 'xyz789'}
229
response = requests.get('https://httpbin.org/cookies', cookies=cookies)
230
```
231
232
### Session Cookie Persistence
233
234
```python
235
import requests
236
237
# Cookies persist across requests in a session
238
session = requests.Session()
239
session.get('https://httpbin.org/cookies/set/sessionid/abc123')
240
241
# Cookie is automatically sent in subsequent requests
242
response = session.get('https://httpbin.org/cookies')
243
data = response.json()
244
print(data['cookies']['sessionid']) # 'abc123'
245
```
246
247
### Manual Cookie Management
248
249
```python
250
import requests
251
from requests.cookies import RequestsCookieJar
252
253
# Create custom cookie jar
254
jar = RequestsCookieJar()
255
jar.set('custom_cookie', 'custom_value', domain='example.com')
256
jar.set('another_cookie', 'another_value')
257
258
# Use jar with request
259
response = requests.get('https://example.com', cookies=jar)
260
261
# Examine cookies
262
for name, value in jar.items():
263
print(f"{name}: {value}")
264
265
# Get cookies for specific domain
266
domain_cookies = jar.get_dict(domain='example.com')
267
print(domain_cookies)
268
```
269
270
### Cookie Jar Operations
271
272
```python
273
import requests
274
275
# Get cookies from response
276
response = requests.get('https://httpbin.org/cookies/set/foo/bar')
277
jar = response.cookies
278
279
# Cookie jar behaves like a dict
280
print(jar['foo']) # 'bar'
281
print(jar.get('foo')) # 'bar'
282
print(list(jar.keys())) # ['foo']
283
print(list(jar.values())) # ['bar']
284
print(list(jar.items())) # [('foo', 'bar')]
285
286
# Copy cookie jar
287
new_jar = jar.copy()
288
289
# Update from dict
290
jar.update({'baz': 'qux'})
291
292
# Check domains and paths
293
print(jar.list_domains())
294
print(jar.list_paths())
295
print(jar.multiple_domains())
296
```
297
298
### Cookie Utilities
299
300
```python
301
import requests
302
from requests.cookies import cookiejar_from_dict, merge_cookies
303
304
# Create jar from dict
305
cookie_dict = {'session': 'abc123', 'user': 'john'}
306
jar = cookiejar_from_dict(cookie_dict)
307
308
# Use with session
309
session = requests.Session()
310
session.cookies = jar
311
312
# Merge cookies
313
additional_cookies = {'theme': 'dark', 'lang': 'en'}
314
merge_cookies(jar, additional_cookies)
315
316
response = session.get('https://httpbin.org/cookies')
317
```
318
319
### Advanced Cookie Handling
320
321
```python
322
import requests
323
from requests.cookies import RequestsCookieJar
324
325
def manage_cookies():
326
jar = RequestsCookieJar()
327
328
# Set cookies with attributes
329
jar.set('secure_cookie', 'secret_value',
330
domain='api.example.com',
331
path='/secure',
332
secure=True)
333
334
# Set session cookie (no expiry)
335
jar.set('session_id', 'sess_123456')
336
337
# Check cookie existence
338
if 'session_id' in jar:
339
print("Session cookie found")
340
341
# Get cookie with domain/path filtering
342
secure_value = jar.get('secure_cookie',
343
domain='api.example.com',
344
path='/secure')
345
346
# Remove specific cookie
347
if 'old_cookie' in jar:
348
del jar['old_cookie']
349
350
return jar
351
352
# Use custom jar
353
jar = manage_cookies()
354
response = requests.get('https://api.example.com/secure/data', cookies=jar)
355
```
356
357
## Cookie Security
358
359
### Secure Cookie Practices
360
361
```python
362
import requests
363
from requests.cookies import RequestsCookieJar
364
365
# Always use HTTPS for sensitive cookies
366
jar = RequestsCookieJar()
367
jar.set('auth_token', 'sensitive_token',
368
domain='secure-api.com',
369
secure=True, # Only send over HTTPS
370
httponly=True) # Not accessible via JavaScript
371
372
# Use with secure request
373
response = requests.get('https://secure-api.com/data', cookies=jar)
374
```
375
376
### Cookie Domain Validation
377
378
```python
379
import requests
380
381
def safe_cookie_handling(url, cookies):
382
"""Safely handle cookies with domain validation."""
383
session = requests.Session()
384
385
# Let requests handle cookie domain validation
386
response = session.get(url, cookies=cookies)
387
388
# Check which cookies were actually sent
389
request_cookies = response.request.headers.get('Cookie', '')
390
print(f"Cookies sent: {request_cookies}")
391
392
return response
393
394
# Example usage
395
cookies = {'token': 'abc123'}
396
response = safe_cookie_handling('https://api.example.com', cookies)
397
```