真正实现配置复用与模块化靠的是Session+自定义配置类/工厂函数,而非直接调用requests.request();Session天然支持连接复用、共享headers/auth/cookies/超时/重试,是推荐方式。

直接用 requests.request() 构造函数本身并不支持配置复用或模块化管理——它只是一个底层通用接口,每次调用都新建请求、不保留状态、也不自动复用连接。真正实现配置复用与模块化,靠的是上层封装机制,核心是 Session + 自定义配置类/工厂函数,而非直接操作 request()。
用 Session 封装共用配置
这是最自然、最推荐的方式。Session 天然支持跨请求复用连接、共享 headers、auth、cookies、超时、重试策略等:
- 创建一个预设好 headers、timeout、认证信息的 Session 实例,作为“请求客户端”统一出口
- 所有业务请求都通过该 Session 发起,避免重复传参
- 连接池、SSL 验证、代理等也随 Session 统一管理
示例:
pythonimport requests
<p>class APIClient:
def <strong>init</strong>(self, base_url, timeout=(3, 10), user_agent="MyApp/1.0"):
self.session = requests.Session()
self.base_url = base_url.rstrip("/")
self.session.headers.update({"User-Agent": user_agent})
self.timeout = timeout</p><h1>可选:挂载带连接池和重试的 adapter</h1><pre class="brush:php;toolbar:false;"> adapter = requests.adapters.HTTPAdapter(
pool_connections=10,
pool_maxsize=20,
max_retries=2
)
self.session.mount("http://", adapter)
self.session.mount("https://", adapter)
def get(self, path, **kwargs):
url = f"{self.base_url}{path}"
return self.session.get(url, timeout=self.timeout, **kwargs)
def post(self, path, **kwargs):
url = f"{self.base_url}{path}"
return self.session.post(url, timeout=self.timeout, **kwargs)使用
client = APIClient("https://www.php.cn/link/710ba53b0d353329706ee1bedf4b9b39") resp = client.get("/users") data = resp.json()
用函数工厂生成定制化请求函数
适合轻量级、配置差异明确的场景(如不同环境、不同认证方式)。用闭包把固定参数“冻结”进函数里:
- 每个工厂函数返回一个已绑定 base_url、headers、auth 的专用请求函数
- 调用时只需传动态参数(如 path、json),逻辑清晰、无状态污染
- 便于单元测试和 mock
示例:
pythonimport requests
<p>def make_requester(base_url, auth=None, headers=None, timeout=(3, 10)):
base_headers = {"User-Agent": "MyApp/1.0"}
if headers:
base_headers.update(headers)</p><pre class="brush:php;toolbar:false;">def requester(method, path, **kwargs):
url = f"{base_url.rstrip('/')}{path}"
kwargs.setdefault("headers", {}).update(base_headers)
kwargs.setdefault("auth", auth)
kwargs.setdefault("timeout", timeout)
return requests.request(method, url, **kwargs)
return requester生成生产环境请求器
prod_req = make_requester("https://www.php.cn/link/fa731652c97f2dd6f285126b577e0d1e", auth=("u", "p"))
生成测试环境请求器
test_req = make_requester("https://www.php.cn/link/4129970ba309510811271efc661fd669", headers={"X-Env": "test"})
使用
resp = prod_req("GET", "/status")
用配置字典驱动请求行为
把请求模板(method、url、headers、params 等)写成结构化配置,配合通用执行函数,实现声明式调用:
- 配置与逻辑分离,适合多接口、多版本、YAML/JSON 配置驱动的项目
- 可结合 jinja2 模板、环境变量注入动态值(如 token、host)
- 便于生成文档、做请求审计或录制回放
示例(简化版):
pythonimport requests
<p>REQUEST_CONFIGS = {
"get_user": {
"method": "GET",
"url": "<a href="https://www.php.cn/link/710ba53b0d353329706ee1bedf4b9b39/users/%7Buser_id">https://www.php.cn/link/710ba53b0d353329706ee1bedf4b9b39/users/{user_id</a>}",
"headers": {"Accept": "application/json"},
"timeout": (3, 15),
},
"create_order": {
"method": "POST",
"url": "<a href="https://www.php.cn/link/710ba53b0d353329706ee1bedf4b9b39/orders">https://www.php.cn/link/710ba53b0d353329706ee1bedf4b9b39/orders</a>",
"headers": {"Content-Type": "application/json"},
"json": {"items": []},
}
}</p><p>def call_api(config_key, <strong>context):
config = REQUEST_CONFIGS[config_key].copy()
url = config.pop("url").format(</strong>context) # 替换路径变量
method = config.pop("method")
return requests.request(method, url, <strong>config, </strong>context)</p><h1>使用</h1><p>resp = call_api("get_user", user_id=123)
</p>
不复杂但容易忽略:真正复用的不是 request() 函数本身,而是它背后的 Session 实例、预设的 adapter、封装好的类或闭包。模块化关键在于把“变”与“不变”分清楚——把不变的配置抽出来,让业务代码只关注变化的数据和路径。










