Sessions
suggest changeIn web programming, HTTP is a stateless protocol: every request is executed independently without inherent memory of preceding requests. Sessions bridge this gap by persisting state across multiple HTTP interactions. In Python, sessions are used in two primary contexts:
- Client-side HTTP sessions (via
requests.Sessionoraiohttp.ClientSession): Persisting cookies, connection pools, and authentication across outbound requests. - Server-side web sessions (via frameworks like Flask or Django): Tracking authenticated user state and application variables across incoming browser requests.
1. Client-Side Sessions with requests.Session
When making multiple HTTP requests to the same host using standard functions like requests.get() or requests.post(), Python opens and closes a new TCP connection (and performs a new TLS handshake) for every single call.
Using requests.Session() provides two major benefits:
- Connection Pooling & Keep-Alive: Reuses underlying TCP sockets across requests, drastically speeding up network operations.
- Cookie Persistence: Automatically retains and forwards cookies returned in
Set-Cookieheaders across requests.
Basic Usage and Context Manager
Always use a with statement so the underlying connection pool and sockets are properly closed when finished:
import requests
with requests.Session() as session:
# 1. Log in to service
login_payload = {'username': 'alice', 'password': 'secret_password'}
response = session.post('https://httpbin.org/post', data=login_payload)
# 2. Subsequent requests automatically carry any session cookies set by server
profile_response = session.get('https://httpbin.org/cookies')
print(profile_response.json())
2. Session-Level Headers and Authentication
You can attach headers, query parameters, and credentials to a Session once; they will be automatically included in all subsequent requests made through that session:
import requests
from requests.auth import HTTPBasicAuth
session = requests.Session()
# Set default authorization and headers for all future requests
session.auth = HTTPBasicAuth('api_user', 'api_token_123')
session.headers.update({
'User-Agent': 'InternalMicroservice/1.0',
'Accept': 'application/json'
})
# Both requests inherit the headers and auth credentials:
res1 = session.get('https://httpbin.org/basic-auth/api_user/api_token_123')
res2 = session.get('https://httpbin.org/headers')
print(f"Status: {res1.status_code}")
print(res2.json()['headers']['User-Agent']) # Output: InternalMicroservice/1.0
session.close()
Individual request parameters can still override session-level settings:
# Overrides User-Agent just for this single call:
session.get('https://httpbin.org/headers', headers={'User-Agent': 'CustomAgent/2.0'})
3. Configuring Retries and Connection Pools with HTTPAdapter
By mounting a custom HTTPAdapter backed by urllib3.util.Retry, you can configure automatic exponential backoff retries for transient HTTP errors (such as 502, 503, 504 status codes):
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
session = requests.Session()
# Configure retry strategy: 3 retries, exponential backoff, retry on specific HTTP statuses
retry_strategy = Retry(
total=3,
backoff_factor=1, # Wait 0s, 2s, 4s between attempts
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "OPTIONS"]
)
# Mount adapter with larger connection pool
adapter = HTTPAdapter(
max_retries=retry_strategy,
pool_connections=20,
pool_maxsize=20
)
session.mount('https://', adapter)
session.mount('http://', adapter)
response = session.get('https://httpbin.org/status/200')
print(f"Response status: {response.status_code}")
4. Server-Side Sessions in Flask
On the server side, web applications use sessions to remember logged-in users across page loads. In Flask, session data is cryptographically signed and stored inside a client cookie:
from datetime import timedelta
from flask import Flask, session, redirect, url_for, request
app = Flask(__name__)
# Secret key used to cryptographically sign session cookies
app.secret_key = 'super-secret-cryptographic-key-change-in-production'
# Configure session cookie security
app.config.update(
SESSION_COOKIE_SECURE=True, # Only send over HTTPS
SESSION_COOKIE_HTTPONLY=True, # Prevent JavaScript document.cookie access (mitigate XSS)
SESSION_COOKIE_SAMESITE='Lax', # Mitigate CSRF attacks
PERMANENT_SESSION_LIFETIME=timedelta(hours=2)
)
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
if username == 'admin' and password == 'password123':
session.permanent = True
session['user_id'] = 42
session['username'] = username
return {"status": "logged_in"}
return {"error": "Invalid credentials"}, 401
@app.route('/dashboard')
def dashboard():
# Check if session exists
if 'user_id' not in session:
return {"error": "Unauthorized"}, 401
return {"message": f"Welcome back, {session['username']}!"}
@app.route('/logout', methods=['POST'])
def logout():
# Clear all session keys
session.clear()
return {"status": "logged_out"}
Best Practices
- Always Close Client Sessions: Use
with requests.Session() as session:to guarantee underlying sockets are returned to the pool and freed. - Never Store Sensitive Plaintext in Client-Side Signed Sessions: In frameworks like Flask (without server-side extensions like Flask-Session), session data is cryptographically signed but not encrypted. Anyone can read the payload by base64-decoding the cookie. Store only opaque user identifiers (
user_id), not passwords or tokens. - Set Security Cookie Flags: Always enable
HttpOnly,Secure, andSameSiteon session cookies to defend against Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF).