Chapter 18 · Security Best Practices
Chapter goals: Master security risks in HTTP requests and their countermeasures.
18.1 Enforcing HTTPS
python
import requests
# Always use HTTPS
resp = requests.get('https://api.example.com/data')
# Prevent redirect downgrade to HTTP (prevents downgrade attacks)
resp = requests.get('https://api.example.com/data', allow_redirects=True)18.2 Protecting Sensitive Information
python
import os
import requests
# Wrong: hard-coded secret
# resp = requests.get('https://api.example.com', headers={'Authorization': 'Bearer sk-xxx'})
# Correct: read from environment variable
api_key = os.environ.get('API_KEY')
if not api_key:
raise ValueError('Please set the API_KEY environment variable')
resp = requests.get(
'https://api.example.com',
headers={'Authorization': f'Bearer {api_key}'}
)18.3 URL Injection Prevention
python
import requests
from urllib.parse import urlencode
# Dangerous: directly concatenating user input into URL
# url = f'https://api.example.com/search?q={user_input}'
# Safe: use params argument
params = {'q': user_input}
resp = requests.get('https://api.example.com/search', params=params)18.4 SSL Certificate Verification
python
import requests
# Production must verify certificates
resp = requests.get('https://api.example.com', verify=True) # default
# Internal self-signed certs: specify CA bundle
resp = requests.get('https://internal.example.com', verify='/path/to/ca.pem')
# Never set verify=False in production18.5 Rate Limiting and Anti-Spam
python
import requests
import time
def rate_limited_get(url: str, max_retries: int = 3):
for attempt in range(max_retries):
try:
resp = requests.get(url, timeout=10)
if resp.status_code == 429: # rate limited
wait = int(resp.headers.get('Retry-After', 60))
time.sleep(wait)
continue
resp.raise_for_status()
return resp
except requests.exceptions.RequestException as e:
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt) # exponential backoff18.6 Chapter Summary
- Always use HTTPS; never degrade to HTTP;
- Read API keys and other sensitive info from environment variables;
- Use params instead of string concatenation to build URLs;
- SSL certificate verification must be enabled in production.
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. What is the correct SSL verification approach for production?
2. What is the best practice for preventing URL injection?
3. Where should API keys be stored?
4. What does HTTP 429 status code mean?
🛠️ Hands-on Practice
- Implement a safe pattern that reads the API Key from environment variables.
- Test the difference between URL encoding and string concatenation.
- Implement a rate-limited request function.
After completing the exercises, move to Next chapter: Production Deployment and Monitoring.