You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用requests_cache+MongoDB时首次请求后连接关闭致二次请求失败

解决requests_cache使用MongoDB后端时第二次请求抛出"Cannot use MongoClient after close"错误

问题场景

使用requests_cache并指定MongoDB作为缓存后端时,首次调用requests.get()可正常执行,但第二次调用会抛出pymongo.errors.InvalidOperation: Cannot use MongoClient after close错误。切换为默认SQLite缓存后端则无此问题。

用户代码示例:

import requests
import requests_cache
from pymongo import MongoClient

requests_cache.install_cache(
    cache_name='http_cache',
    backend='mongodb',
    connection=MongoClient('mongodb://localhost:27017/'),
    db_name='your_database',
)
# 此请求正常
requests.get("http://hello.com/1")

# 此请求抛出"Cannot use MongoClient after close"错误
requests.get("http://hello.com/2")

报错信息:

pymongo.errors.InvalidOperation: Cannot use MongoClient after close

问题原因

当手动传入外部创建的MongoClient实例时,requests_cache的MongoDB后端默认会在第一次请求完成后关闭该连接,但后续请求仍会尝试复用这个已关闭的客户端实例,从而触发错误。而SQLite后端不存在自动关闭外部连接的逻辑,因此无此问题。

解决方案

方案1:让requests_cache自行管理MongoClient(推荐)

无需手动创建MongoClient,通过host参数指定MongoDB地址,由requests_cache内部创建并维护连接生命周期:

import requests
import requests_cache

requests_cache.install_cache(
    cache_name='http_cache',
    backend='mongodb',
    host='mongodb://localhost:27017/',
    db_name='your_database',
)

requests.get("http://hello.com/1")
requests.get("http://hello.com/2")  # 可正常执行

方案2:禁止requests_cache关闭外部传入的MongoClient

如果必须手动管理MongoClient,添加close_connection=False参数,阻止requests_cache关闭你的客户端实例:

import requests
import requests_cache
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
requests_cache.install_cache(
    cache_name='http_cache',
    backend='mongodb',
    connection=client,
    db_name='your_database',
    close_connection=False  # 关键配置
)

requests.get("http://hello.com/1")
requests.get("http://hello.com/2")  # 可正常执行

注意:此方案下需要你自行在程序结束时关闭client,避免连接资源泄漏。

内容的提问来源于stack exchange,提问作者David Portabella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 13:52:12