0
# Sessions
1
2
Session objects provide a way to persist certain parameters across requests, enabling connection pooling, cookie persistence, and default configuration. Sessions are essential for maintaining state across multiple requests and improving performance through connection reuse.
3
4
## Capabilities
5
6
### Session Class
7
8
The Session class provides persistent configuration and connection pooling across multiple requests.
9
10
```python { .api }
11
class Session:
12
"""
13
Session object for persisting settings across requests.
14
15
Attributes:
16
- headers: Default headers for all requests
17
- cookies: Cookie jar for persistent cookies
18
- auth: Default authentication
19
- proxies: Default proxy configuration
20
- hooks: Event hooks
21
- params: Default URL parameters
22
- verify: Default SSL verification setting
23
- cert: Default client certificate
24
- max_redirects: Maximum number of redirects to follow
25
- trust_env: Whether to trust environment variables for configuration
26
- stream: Default streaming setting
27
- adapters: OrderedDict of mounted transport adapters
28
"""
29
30
def __init__(self):
31
"""Initialize a new Session."""
32
33
def __enter__(self):
34
"""Context manager entry."""
35
36
def __exit__(self, *args):
37
"""Context manager exit."""
38
39
def prepare_request(self, request: Request) -> PreparedRequest:
40
"""
41
Prepare a Request object for sending.
42
43
Parameters:
44
- request: Request object to prepare
45
46
Returns:
47
PreparedRequest object ready to send
48
"""
49
50
def request(self, method: str, url: str, **kwargs) -> Response:
51
"""
52
Send a request using the session configuration.
53
54
Parameters:
55
- method: HTTP method
56
- url: URL for the request
57
- **kwargs: additional request parameters
58
59
Returns:
60
Response object
61
"""
62
63
def get(self, url: str, **kwargs) -> Response:
64
"""Send a GET request using session configuration."""
65
66
def options(self, url: str, **kwargs) -> Response:
67
"""Send an OPTIONS request using session configuration."""
68
69
def head(self, url: str, **kwargs) -> Response:
70
"""Send a HEAD request using session configuration."""
71
72
def post(self, url: str, data=None, json=None, **kwargs) -> Response:
73
"""Send a POST request using session configuration."""
74
75
def put(self, url: str, data=None, **kwargs) -> Response:
76
"""Send a PUT request using session configuration."""
77
78
def patch(self, url: str, data=None, **kwargs) -> Response:
79
"""Send a PATCH request using session configuration."""
80
81
def delete(self, url: str, **kwargs) -> Response:
82
"""Send a DELETE request using session configuration."""
83
84
def send(self, request: PreparedRequest, **kwargs) -> Response:
85
"""
86
Send a prepared request.
87
88
Parameters:
89
- request: PreparedRequest object
90
- **kwargs: additional sending parameters like timeout, verify, etc.
91
92
Returns:
93
Response object
94
"""
95
96
def merge_environment_settings(self, url: str, proxies: dict, stream: bool,
97
verify: Union[bool, str], cert: Union[str, tuple]):
98
"""
99
Merge environment settings with session settings.
100
101
Parameters:
102
- url: Request URL
103
- proxies: Proxy configuration
104
- stream: Stream setting
105
- verify: SSL verification setting
106
- cert: Client certificate setting
107
108
Returns:
109
Dict of merged settings
110
"""
111
112
def get_adapter(self, url: str):
113
"""
114
Get the appropriate adapter for the given URL.
115
116
Parameters:
117
- url: URL to get adapter for
118
119
Returns:
120
Adapter instance
121
"""
122
123
def close(self):
124
"""Close the session and clean up resources."""
125
126
def mount(self, prefix: str, adapter):
127
"""
128
Register an adapter for a URL prefix.
129
130
Parameters:
131
- prefix: URL prefix (e.g., 'https://')
132
- adapter: Adapter instance to mount
133
"""
134
```
135
136
### Session Factory Function
137
138
Convenience function to create a new session.
139
140
```python { .api }
141
def session() -> Session:
142
"""
143
Create and return a new Session object.
144
145
Returns:
146
New Session instance
147
"""
148
```
149
150
## Usage Examples
151
152
### Basic Session Usage
153
154
```python
155
import requests
156
157
# Create a session
158
s = requests.Session()
159
160
# Set default headers and authentication
161
s.headers.update({'User-Agent': 'MyApp/1.0'})
162
s.auth = ('username', 'password')
163
164
# Make requests using the session
165
response1 = s.get('https://api.example.com/data')
166
response2 = s.post('https://api.example.com/update', json={'key': 'value'})
167
168
# Cookies are automatically persisted
169
response3 = s.get('https://api.example.com/profile') # Cookies from previous requests are sent
170
171
# Close the session
172
s.close()
173
```
174
175
### Session as Context Manager
176
177
```python
178
import requests
179
180
# Use session as a context manager for automatic cleanup
181
with requests.Session() as s:
182
s.headers.update({'Authorization': 'Bearer token123'})
183
184
response = s.get('https://api.example.com/protected')
185
data = response.json()
186
187
# Process data...
188
189
# Session is automatically closed when exiting the context
190
```
191
192
### Persistent Configuration
193
194
```python
195
import requests
196
197
s = requests.Session()
198
199
# Set persistent configuration
200
s.headers.update({
201
'User-Agent': 'MyApp/2.0',
202
'Accept': 'application/json'
203
})
204
s.auth = ('api_user', 'api_pass')
205
s.proxies = {'http': 'http://proxy.example.com:8080'}
206
s.verify = '/path/to/ca-bundle.crt'
207
208
# All requests will use these settings by default
209
response1 = s.get('https://api.example.com/users')
210
response2 = s.post('https://api.example.com/data', json={'name': 'John'})
211
212
# Override settings for specific requests
213
response3 = s.get('https://other-api.com/data', auth=None, verify=False)
214
```
215
216
### Connection Pooling Benefits
217
218
```python
219
import requests
220
221
# Without session - new connection for each request
222
for i in range(10):
223
requests.get('https://api.example.com/data/' + str(i)) # 10 separate connections
224
225
# With session - connection pooling
226
with requests.Session() as s:
227
for i in range(10):
228
s.get('https://api.example.com/data/' + str(i)) # Reuses connections
229
```
230
231
## Session Attributes
232
233
Sessions have several configurable attributes:
234
235
- **headers**: `CaseInsensitiveDict` - Default headers for all requests
236
- **cookies**: `RequestsCookieJar` - Persistent cookie storage
237
- **auth**: `AuthType` - Default authentication handler
238
- **proxies**: `Dict[str, str]` - Default proxy configuration
239
- **hooks**: `Dict[str, List[Callable]]` - Event hooks for request/response processing
240
- **params**: `Dict[str, str]` - Default URL parameters
241
- **verify**: `Union[bool, str]` - Default SSL certificate verification
242
- **cert**: `Union[str, Tuple[str, str]]` - Default client certificate
243
- **max_redirects**: `int` - Maximum redirects to follow (default: 30)
244
- **trust_env**: `bool` - Trust environment variables for proxy config
245
- **stream**: `bool` - Default streaming behavior
246
247
## Session Methods vs Module Functions
248
249
Session methods provide the same interface as module-level functions but with persistent configuration:
250
251
| Module Function | Session Method | Benefit |
252
|----------------|----------------|---------|
253
| `requests.get()` | `session.get()` | Persistent headers, cookies, auth |
254
| `requests.post()` | `session.post()` | Connection pooling |
255
| `requests.put()` | `session.put()` | Proxy configuration |
256
| `requests.delete()` | `session.delete()` | SSL settings |
257
258
Session methods inherit all session configuration but can be overridden with method-specific parameters.