Linux中用Python的requests库处理HTTP API

81 阅读2分钟

requests库是Python中广泛使用的HTTP客户端库,以其简洁的API和强大的功能成为处理HTTP请求的首选工具。在Linux环境下,结合requests库可轻松实现API调用、数据抓取及自动化交互。


核心优势****

1. 简洁易用:相比标准库urllib,requests提供更直观的API设计。

2. 功能全面:支持会话保持、Cookie管理、SSL验证、代理设置等高级功能。

3. 生态丰富:与json、pandas等库无缝集成,便于数据处理。


基础用法示例****

1. 发送GET请求****

python

 import requests
  
 response = requests.get("api.example.com/data")
 print(response.status_code) # 输出状态码(200表示成功)
 print(response.json()) # 解析JSON响应内容

2. 发送POST请求(JSON数据)****

python

 import requests
 import json
  
 url = "api.example.com/create"
 data = {"name": "test", "value": 123}
  
 response = requests.post(url, json=data) # 自动设置Content-Type为application/json
 print(response.text) # 输出原始响应文本

3. 处理认证与头部****

python

 # Basic认证
 response = requests.get("secure.example.com/api", auth=("user", "pass"))
  
 # 自定义请求头
 headers = {"X-Custom-Header": "value"}
 response = requests.get("api.example.com", headers=headers)

高级功能应用****

1. 会话保持(Session对象)****

自动处理Cookie和连接池,适合登录态维护:

python

 with requests.Session() as session:
 session.post("example.com/login", data={"user": "admin", "pass": "secret"})
 response = session.get("example.com/dashboard") # 自动携带Cookie
 print(response.text)

2. 超时与重试机制****

python

 from requests.adapters import HTTPAdapter
 from requests.packages.urllib3.util.retry import Retry
  
 # 配置重试策略
 retry_strategy = Retry(
 total=3, # 最大重试次数
 status_forcelist=[500, 502, 503, 504], # 针对特定状态码重试
 method_whitelist=["GET", "POST"] # 允许重试的HTTP方法
 )
  
 # 绑定到Session
 session = requests.Session()
 adapter = HTTPAdapter(max_retries=retry_strategy)
 session.mount("https://", adapter)
 session.mount("http://", adapter)
  
 # 发送请求(自动应用重试)
 response = session.get("api.example.com", timeout=5) # 连接/读取超时5秒

3. 文件上传与下载****

python

 # 上传文件
 files = {"file": open("report.pdf", "rb")}
 response = requests.post("api.example.com/upload", files=files)
  
 # 下载文件
 response = requests.get("example.com/image.jpg", stream=True)
 with open("image.jpg", "wb") as f:
 for chunk in response.iter_content(1024): # 分块写入避免内存溢出
 f.write(chunk)

错误处理与调试****

1. 

异常捕获

2. 

3. 

python

4. 

5. 

 try:
 response = requests.get("api.example.com", timeout=3)
 response.raise_for_status() # 非200状态码抛出HTTPError
 except requests.exceptions.RequestException as e:
 print(f"请求失败: {e}")

6. 

7. 

调试工具

8. 

1. 启用调试日志:

2. 

python

3. 

4. 

 import logging
 import http.client
 http.client.HTTPConnection.debuglevel = 1
 logging.basicConfig()
 logging.getLogger().setLevel(logging.DEBUG)

5. 

6. 使用response.request.headers查看实际发送的请求头。


性能优化建议****

· 连接池复用:通过Session对象避免重复建立TCP连接。

· 异步请求:对高并发场景,可结合aiohttp或httpx(异步版requests)。

· 缓存响应:对静态数据使用requests-cache库减少重复请求。

通过requests库的灵活应用,开发者可在Linux环境中高效完成API交互,提升自动化脚本的可靠性和开发效率。