0
# Session Management
1
2
Session classes for managing persistent connections, cookies, authentication, and other settings across multiple requests. Sessions provide connection pooling, configuration management, and state persistence, making them ideal for applications that make multiple requests to the same server or API.
3
4
## Capabilities
5
6
### Session Class
7
8
The synchronous Session class provides persistent connection management and configuration sharing across multiple HTTP requests.
9
10
```python { .api }
11
class Session:
12
"""
13
A Requests session for persistent configuration and connection management.
14
15
Provides cookie persistence, connection-pooling, and configuration.
16
Supports context manager protocol for automatic resource cleanup.
17
"""
18
19
def __init__(
20
self,
21
*,
22
retries: RetryType = DEFAULT_RETRIES,
23
quic_cache_layer: CacheLayerAltSvcType | None = None,
24
**kwargs
25
):
26
"""
27
Initialize a new Session.
28
29
Args:
30
retries: Default retry configuration for all requests
31
quic_cache_layer: QUIC connection cache layer
32
**kwargs: Additional configuration options
33
"""
34
35
def request(
36
self,
37
method: HttpMethodType,
38
url: str,
39
*,
40
params: QueryParameterType | None = None,
41
data: BodyType | None = None,
42
json: Any | None = None,
43
headers: HeadersType | None = None,
44
cookies: CookiesType | None = None,
45
files: MultiPartFilesType | MultiPartFilesAltType | None = None,
46
auth: HttpAuthenticationType | None = None,
47
timeout: TimeoutType | None = None,
48
allow_redirects: bool = True,
49
proxies: ProxyType | None = None,
50
verify: TLSVerifyType | None = None,
51
stream: bool = False,
52
cert: TLSClientCertType | None = None,
53
hooks: HookType[PreparedRequest | Response] | None = None,
54
) -> Response:
55
"""
56
Send a request using the session configuration.
57
58
Args:
59
method: HTTP method
60
url: Target URL
61
**kwargs: Same parameters as module-level request functions
62
63
Returns:
64
Response object
65
"""
66
67
def get(self, url: str, **kwargs) -> Response:
68
"""Send a GET request using session configuration."""
69
70
def post(self, url: str, **kwargs) -> Response:
71
"""Send a POST request using session configuration."""
72
73
def put(self, url: str, **kwargs) -> Response:
74
"""Send a PUT request using session configuration."""
75
76
def patch(self, url: str, **kwargs) -> Response:
77
"""Send a PATCH request using session configuration."""
78
79
def delete(self, url: str, **kwargs) -> Response:
80
"""Send a DELETE request using session configuration."""
81
82
def head(self, url: str, **kwargs) -> Response:
83
"""Send a HEAD request using session configuration."""
84
85
def options(self, url: str, **kwargs) -> Response:
86
"""Send an OPTIONS request using session configuration."""
87
88
def prepare_request(self, request: Request) -> PreparedRequest:
89
"""
90
Prepare a Request object for transmission.
91
92
Args:
93
request: Request object to prepare
94
95
Returns:
96
PreparedRequest ready for transmission
97
"""
98
99
def send(
100
self,
101
request: PreparedRequest,
102
*,
103
stream: bool = False,
104
timeout: TimeoutType | None = None,
105
verify: TLSVerifyType | None = None,
106
cert: TLSClientCertType | None = None,
107
proxies: ProxyType | None = None,
108
allow_redirects: bool = True,
109
) -> Response:
110
"""
111
Send a PreparedRequest using session configuration.
112
113
Args:
114
request: PreparedRequest to send
115
stream: Whether to stream response content
116
timeout: Request timeout
117
verify: SSL verification
118
cert: Client certificate
119
proxies: Proxy configuration
120
allow_redirects: Follow redirects
121
122
Returns:
123
Response object
124
"""
125
126
def close(self):
127
"""Close all underlying connections and clean up resources."""
128
129
def __enter__(self) -> 'Session':
130
"""Enter context manager."""
131
return self
132
133
def __exit__(self, exc_type, exc_val, exc_tb):
134
"""Exit context manager and clean up resources."""
135
self.close()
136
```
137
138
### AsyncSession Class
139
140
The asynchronous Session class provides the same functionality as Session but for async/await operations.
141
142
```python { .api }
143
class AsyncSession(Session):
144
"""
145
An asynchronous Requests session for concurrent request management.
146
147
Inherits from Session and provides async versions of all methods.
148
Supports async context manager protocol.
149
"""
150
151
def __init__(
152
self,
153
*,
154
retries: RetryType = DEFAULT_RETRIES,
155
quic_cache_layer: CacheLayerAltSvcType | None = None,
156
**kwargs
157
):
158
"""
159
Initialize a new AsyncSession.
160
161
Args:
162
retries: Default retry configuration
163
quic_cache_layer: QUIC connection cache layer
164
**kwargs: Additional configuration options
165
"""
166
167
async def request(
168
self,
169
method: HttpMethodType,
170
url: str,
171
*,
172
params: QueryParameterType | None = None,
173
data: AsyncBodyType | None = None,
174
json: Any | None = None,
175
headers: HeadersType | None = None,
176
cookies: CookiesType | None = None,
177
files: MultiPartFilesType | MultiPartFilesAltType | None = None,
178
auth: AsyncHttpAuthenticationType | None = None,
179
timeout: TimeoutType | None = None,
180
allow_redirects: bool = True,
181
proxies: ProxyType | None = None,
182
verify: TLSVerifyType | None = None,
183
stream: bool = False,
184
cert: TLSClientCertType | None = None,
185
hooks: HookType[PreparedRequest | AsyncResponse] | None = None,
186
) -> AsyncResponse:
187
"""
188
Asynchronously send a request using session configuration.
189
190
Args:
191
method: HTTP method
192
url: Target URL
193
**kwargs: Same parameters as async request functions
194
195
Returns:
196
AsyncResponse object
197
"""
198
199
async def get(self, url: str, **kwargs) -> AsyncResponse:
200
"""Asynchronously send a GET request."""
201
202
async def post(self, url: str, **kwargs) -> AsyncResponse:
203
"""Asynchronously send a POST request."""
204
205
async def put(self, url: str, **kwargs) -> AsyncResponse:
206
"""Asynchronously send a PUT request."""
207
208
async def patch(self, url: str, **kwargs) -> AsyncResponse:
209
"""Asynchronously send a PATCH request."""
210
211
async def delete(self, url: str, **kwargs) -> AsyncResponse:
212
"""Asynchronously send a DELETE request."""
213
214
async def head(self, url: str, **kwargs) -> AsyncResponse:
215
"""Asynchronously send a HEAD request."""
216
217
async def options(self, url: str, **kwargs) -> AsyncResponse:
218
"""Asynchronously send an OPTIONS request."""
219
220
async def send(
221
self,
222
request: PreparedRequest,
223
*,
224
stream: bool = False,
225
timeout: TimeoutType | None = None,
226
verify: TLSVerifyType | None = None,
227
cert: TLSClientCertType | None = None,
228
proxies: ProxyType | None = None,
229
allow_redirects: bool = True,
230
) -> AsyncResponse:
231
"""
232
Asynchronously send a PreparedRequest.
233
234
Args:
235
request: PreparedRequest to send
236
**kwargs: Same parameters as Session.send()
237
238
Returns:
239
AsyncResponse object
240
"""
241
242
async def aclose(self):
243
"""Asynchronously close all connections and clean up resources."""
244
245
def close(self):
246
"""Synchronously close connections (calls aclose() internally)."""
247
248
async def __aenter__(self) -> 'AsyncSession':
249
"""Enter async context manager."""
250
return self
251
252
async def __aexit__(self, exc_type, exc_val, exc_tb):
253
"""Exit async context manager and clean up resources."""
254
await self.aclose()
255
```
256
257
## Session Configuration
258
259
Both Session and AsyncSession classes maintain persistent configuration through instance attributes:
260
261
### Core Session Attributes
262
263
```python { .api }
264
class Session:
265
# Request configuration
266
headers: HeadersType # Default headers for all requests
267
cookies: RequestsCookieJar # Cookie jar for automatic cookie handling
268
auth: HttpAuthenticationType | None # Default authentication
269
proxies: ProxyType # Default proxy configuration
270
271
# SSL/TLS configuration
272
verify: TLSVerifyType # SSL certificate verification
273
cert: TLSClientCertType | None # Client certificate
274
275
# Request behavior
276
max_redirects: int # Maximum number of redirects to follow
277
trust_env: bool # Whether to trust environment variables
278
stream: bool # Default streaming behavior
279
280
# Connection management
281
adapters: dict # Protocol adapters (HTTP/HTTPS)
282
283
# Hook configuration
284
hooks: dict # Request/response lifecycle hooks
285
```
286
287
## Usage Examples
288
289
### Basic Session Usage
290
291
```python
292
import niquests
293
294
# Create a session with persistent configuration
295
session = niquests.Session()
296
297
# Set default headers that will be used for all requests
298
session.headers.update({
299
'User-Agent': 'MyApp/1.0',
300
'Accept': 'application/json'
301
})
302
303
# Set default authentication
304
session.auth = ('username', 'password')
305
306
# Make multiple requests with shared configuration
307
response1 = session.get('https://api.example.com/users')
308
response2 = session.get('https://api.example.com/posts')
309
310
# Session automatically handles cookies
311
login_response = session.post('https://api.example.com/login', {
312
'username': 'user',
313
'password': 'pass'
314
})
315
316
# Subsequent requests will include login cookies automatically
317
protected_response = session.get('https://api.example.com/protected')
318
319
# Clean up resources
320
session.close()
321
```
322
323
### Context Manager Usage
324
325
```python
326
# Recommended: Use as context manager for automatic cleanup
327
with niquests.Session() as session:
328
session.headers['Authorization'] = 'Bearer token123'
329
330
# Make requests using the configured session
331
users = session.get('https://api.example.com/users').json()
332
333
for user in users:
334
profile = session.get(f'https://api.example.com/users/{user["id"]}')
335
print(profile.json())
336
337
# Session is automatically closed when exiting the context
338
```
339
340
### Async Session Usage
341
342
```python
343
import asyncio
344
import niquests
345
346
async def fetch_data_async():
347
async with niquests.AsyncSession() as session:
348
# Configure session
349
session.headers['Accept'] = 'application/json'
350
session.timeout = 30.0
351
352
# Make concurrent requests
353
tasks = [
354
session.get('https://api.example.com/endpoint1'),
355
session.get('https://api.example.com/endpoint2'),
356
session.get('https://api.example.com/endpoint3')
357
]
358
359
responses = await asyncio.gather(*tasks)
360
361
# Process responses
362
results = []
363
for response in responses:
364
data = await response.json()
365
results.append(data)
366
367
return results
368
369
# Run async function
370
results = asyncio.run(fetch_data_async())
371
```
372
373
### Advanced Session Configuration
374
375
```python
376
from niquests import Session, TimeoutConfiguration, RetryConfiguration
377
378
# Create session with advanced configuration
379
session = Session(
380
retries=RetryConfiguration(total=3, backoff_factor=0.5),
381
)
382
383
# Configure timeouts
384
session.timeout = TimeoutConfiguration(connect=5.0, read=30.0)
385
386
# Configure SSL verification
387
session.verify = '/path/to/ca-bundle.crt'
388
session.cert = ('/path/to/client.crt', '/path/to/client.key')
389
390
# Configure proxy
391
session.proxies = {
392
'http': 'http://proxy.example.com:8080',
393
'https': 'https://proxy.example.com:8443'
394
}
395
396
# Add request hooks
397
def log_request(request, *args, **kwargs):
398
print(f"Sending {request.method} request to {request.url}")
399
400
def log_response(response, *args, **kwargs):
401
print(f"Received {response.status_code} response")
402
403
session.hooks = {
404
'pre_request': [log_request],
405
'response': [log_response]
406
}
407
408
# Use configured session
409
response = session.get('https://api.example.com/data')
410
```
411
412
### Session vs Module-Level Functions
413
414
**Use Sessions when:**
415
- Making multiple requests to the same server
416
- Need to persist cookies between requests
417
- Want to share configuration (headers, auth, proxies) across requests
418
- Need connection pooling for better performance
419
- Implementing authentication flows
420
421
**Use module-level functions when:**
422
- Making single, standalone requests
423
- Each request needs completely different configuration
424
- Simple, one-off HTTP operations
425
- Prototyping or testing
426
427
## Performance Benefits
428
429
Sessions provide significant performance benefits:
430
431
1. **Connection Pooling**: Reuses underlying TCP connections
432
2. **Cookie Management**: Automatic cookie handling without manual intervention
433
3. **Configuration Sharing**: Reduces overhead of setting headers/auth per request
434
4. **DNS Caching**: Reduces DNS lookup overhead for repeated requests
435
5. **SSL Session Reuse**: Reuses SSL handshake results when possible
436
437
## Type Definitions
438
439
```python { .api }
440
CacheLayerAltSvcType = Any # QUIC cache layer interface
441
RequestsCookieJar = CookieJar # Cookie jar implementation
442
```