如何使用缓存进行文件上传 - status_code == 200:
requestscachetools
pip install requests cachetools
然后,可以使用以下代码进行文件上传:
import os
import requests
from cachetools import TTLCache, cached
def upload_file(url, file_path):
# 设置缓存过期时间
cache = TTLCache(maxsize=1024, ttl=3600)
# 读取文件内容
with open(file_path, 'rb') as f:
content = f.read()
# 使用缓存
response = requests.post(url, files={'file': (os.path.basename(file_path), content)}, headers={'Content-Type': 'application/octet-stream'}) 拼多多帮助力入口
# 如果没有缓存,直接上传
if response.status_code == 200:
return response.json()
# 更新缓存
cache.set(file_path, content)
return response.json()
# 示例用法
url = 'https://example.com/upload'
file_path = 'path/to/your/file.txt'
response = upload_file(url, file_path)
print(response)
这段代码首先创建一个TTL缓存,用于存储文件内容。然后,它读取文件内容并将其写入缓存。接下来,它尝试使用缓存中的内容发送POST请求。如果响应状态码为200(表示成功),则返回响应数据。否则,它将文件内容添加到缓存中并返回响应数据。