实际应用和最佳实践
现在你已经学会了如何设置各种类型的自定义头部,让我们探讨一些在实际场景中使用头部的实际应用和最佳实践。
发送和接收 JSON 数据
在使用现代 API 时,JSON 是最常见的数据格式。让我们看看如何为 JSON 请求正确设置头部:
- 创建一个名为
json_requests.py 的新文件
- 添加以下代码:
import requests
import json
url = 'https://httpbin.org/post' ## This endpoint accepts POST requests
## Data to send
data = {
'name': 'John Doe',
'email': 'john@example.com',
'message': 'Hello, world!'
}
## Set appropriate headers for JSON
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
## Method 1: Using the json parameter (recommended)
print("Method 1: Using the json parameter")
response = requests.post(url, json=data, headers=headers)
print(f"Status Code: {response.status_code}")
print(response.json()['headers']) ## Show the headers received
print(f"\nData sent (as received by server): {response.json()['json']}")
## Method 2: Manually converting to JSON
print("\nMethod 2: Manually converting to JSON")
json_data = json.dumps(data)
response = requests.post(url, data=json_data, headers=headers)
print(f"Status Code: {response.status_code}")
print(response.json()['headers']) ## Show the headers received
print(f"\nData sent (as received by server): {response.json()['json']}")
- 运行脚本:
python json_requests.py
你应该看到类似于以下的输出:
Method 1: Using the json parameter
Status Code: 200
{'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '72', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'X-Amzn-Trace-Id': 'Root=1-6430ab12-abc123def456'}
Data sent (as received by server): {'name': 'John Doe', 'email': 'john@example.com', 'message': 'Hello, world!'}
Method 2: Manually converting to JSON
Status Code: 200
{'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '72', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'X-Amzn-Trace-Id': 'Root=1-6430ab13-abc123def456'}
Data sent (as received by server): {'name': 'John Doe', 'email': 'john@example.com', 'message': 'Hello, world!'}
请注意,这两种方法都有效,但方法 1 更方便,因为 Requests 库为你处理了 JSON 转换。
使用默认头部创建可重用的会话(Session)
如果你需要使用相同的头部进行多个请求,使用 Session 对象可以节省时间并使你的代码更简洁:
- 创建一个名为
session_headers.py 的新文件
- 添加以下代码:
import requests
## Create a session object
session = requests.Session()
## Set default headers for all requests made with this session
session.headers.update({
'User-Agent': 'MyCustomApp/1.0',
'Accept-Language': 'en-US,en;q=0.9',
'X-API-Key': 'my_session_api_key'
})
## Make a request using the session - it will include our default headers
print("First request with session:")
response = session.get('https://httpbin.org/headers')
print(response.json())
## Add a custom header just for this request
print("\nSecond request with additional header:")
response = session.get('https://httpbin.org/headers',
headers={'X-Custom-Header': 'Just for this request'})
print(response.json())
## Original headers remain unchanged for future requests
print("\nThird request (original headers only):")
response = session.get('https://httpbin.org/headers')
print(response.json())
- 运行脚本:
python session_headers.py
你应该看到类似于以下的输出:
First request with session:
{'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9', 'Host': 'httpbin.org', 'User-Agent': 'MyCustomApp/1.0', 'X-API-Key': 'my_session_api_key', 'X-Amzn-Trace-Id': 'Root=1-6430ab45-abc123def456'}}
Second request with additional header:
{'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9', 'Host': 'httpbin.org', 'User-Agent': 'MyCustomApp/1.0', 'X-API-Key': 'my_session_api_key', 'X-Custom-Header': 'Just for this request', 'X-Amzn-Trace-Id': 'Root=1-6430ab46-abc123def456'}}
Third request (original headers only):
{'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9', 'Host': 'httpbin.org', 'User-Agent': 'MyCustomApp/1.0', 'X-API-Key': 'my_session_api_key', 'X-Amzn-Trace-Id': 'Root=1-6430ab47-abc123def456'}}
使用会话是最佳实践,原因如下:
- 提高性能(连接池)
- 跨请求的头部一致性
- 自动处理 Cookie
- 根据需要添加每个请求的自定义
使用头部的最佳实践
总而言之,以下是在使用 HTTP 头部时要遵循的一些最佳实践:
- 对于对同一域名的多个请求,使用 Session 对象
- 为你要发送的数据正确设置 Content-Type 头部
- 正确处理身份验证 - 尽可能使用内置的身份验证
- 保护敏感信息 - 不要对 API 密钥或令牌进行硬编码
- 仔细遵循 API 文档,了解所需的头部
这是一个演示这些最佳实践的最终示例:
- 创建一个名为
best_practices.py 的新文件
- 添加以下代码:
import requests
import os
## In a real application, get these from environment variables or a secure configuration
## For this example, we're keeping it simple
API_KEY = os.environ.get('API_KEY', 'default_api_key')
BASE_URL = 'https://httpbin.org'
def create_api_client():
"""Create a reusable session with default headers."""
session = requests.Session()
## Set common headers
session.headers.update({
'User-Agent': 'MyApp/1.0',
'X-API-Key': API_KEY,
'Accept': 'application/json'
})
return session
def get_data(client, endpoint):
"""Make a GET request to the specified endpoint."""
url = f"{BASE_URL}/{endpoint}"
response = client.get(url)
return response.json()
def post_data(client, endpoint, data):
"""Make a POST request with JSON data."""
url = f"{BASE_URL}/{endpoint}"
response = client.post(url, json=data)
return response.json()
## Usage example
def main():
## Create the API client
client = create_api_client()
## GET request example
print("Making GET request...")
get_response = get_data(client, 'headers')
print(f"Headers sent: {get_response['headers']}")
## POST request example
print("\nMaking POST request...")
data = {'name': 'John', 'age': 30}
post_response = post_data(client, 'post', data)
print(f"Data received by server: {post_response['json']}")
if __name__ == '__main__':
main()
- 运行脚本:
python best_practices.py
你应该看到类似于以下的输出:
Making GET request...
Headers sent: {'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'MyApp/1.0', 'X-API-Key': 'default_api_key', 'X-Amzn-Trace-Id': 'Root=1-6430ab78-abc123def456'}
Making POST request...
Data received by server: {'name': 'John', 'age': 30}
此示例演示了一种使用自定义头部进行 HTTP 请求的结构化方法,遵循最佳实践,例如创建可重用的会话,将代码组织成函数,以及避免对敏感信息进行硬编码。