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

如何将requests_cache的缓存文件指定到自定义目录?

解决方案:固定requests_cache缓存文件路径

问题根源在于requests_cache.install_cache()只传文件名时,会默认将缓存文件生成在当前工作目录:

  • 直接用python3 main.py运行时,工作目录是脚本所在目录
  • 用exec(open("main.py").read())交互运行时,工作目录是你打开交互环境的目录

要固定缓存位置,只需要给install_cache()传入绝对路径,而不是单纯的文件名。下面提供两种常用方案:

方案1:缓存到用户专属目录(推荐)

将缓存放在用户主目录的.cache文件夹下,适合跨场景共享缓存:

import os
import requests
import requests_cache

# 构建绝对缓存路径:用户主目录/.cache/webpage_cache
cache_path = os.path.expanduser("~/.cache/webpage_cache")
# 确保缓存目录存在,不存在则自动创建
os.makedirs(os.path.dirname(cache_path), exist_ok=True)

requests_cache.install_cache(cache_path)

# 后续原有代码不变
url = input("What URL should I fetch?")
response = requests.get(url)

if response.from_cache:
    print('Retrieved from cache')
else:
    print('Fetched from website')

print(response.text)

方案2:缓存到脚本所在目录的固定子文件夹

如果希望缓存和脚本绑定,只在脚本所在目录生成缓存文件:

import os
import requests
import requests_cache

# 获取脚本自身的绝对目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 构建脚本目录下的cache子文件夹路径
cache_path = os.path.join(script_dir, "cache", "webpage_cache")
# 确保目录存在
os.makedirs(os.path.dirname(cache_path), exist_ok=True)

requests_cache.install_cache(cache_path)

# 后续原有代码不变
url = input("What URL should I fetch?")
response = requests.get(url)

if response.from_cache:
    print('Retrieved from cache')
else:
    print('Fetched from website')

print(response.text)

关键说明

  • os.path.expanduser("~")会自动解析当前用户的主目录(Windows下是C:\Users\用户名,Linux/macOS下是/home/用户名)
  • os.makedirs(..., exist_ok=True)确保缓存目录存在,避免因目录不存在导致的报错
  • 两种方案都能让缓存文件固定在指定位置,不管你用哪种方式运行脚本,都能正常识别和复用缓存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:35:14