API请求可以进行缓存,以减少网络带宽和加快响应时间。 常见的缓存机制包括浏览器缓存,代理服务器缓存以及在应用程序代码中直接对API请求进行缓存。 下面是一个使用Python中的缓存模块的示例,以对API请求进行缓存:
import requests
import json
import functools
import time
import hashlib
from cachecontrol.cache import SimpleCache
from cachecontrol.wrapper import CacheControl
cache = SimpleCache()
# 缓存API请求的装饰器
def api_cache(timeout=3600):
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
# 将请求信息进行哈希
url = function(*args, **kwargs)
encoded_url = hashlib.sha1(url.encode()).hexdigest()
response = cache.get(encoded_url)
if response:
print('Found in cache:', url)
else:
print('Not found in cache:', url)
# 缓存中未找到时,向API请求获取数据
s = requests.Session()
s = CacheControl(s)
response = s.get(url)
cache.set(encoded_url, response.content, expire_after=timeout)
return json.loads(response.content.decode('utf-8'))
return wrapper
return decorator
# 使用装饰器处理API请求,并缓存结果
@api_cache()
def get_data():
url = 'https://example.com/api/data'
return url
data = get_data()
在上面的代码中,装饰器 “api_cache()” 将对API请求返回结果进行缓存,避免重复请求。 每个请求都会以URL为键进行缓存,并将结果存储在缓存中。 由于API数据可能会发生变化,设置了过期时间timeout为1小时,以确保缓存中的数据不会太旧。
下一篇:API请求时间过长