Ubuntu 下 Python 缓存使用指南
一 场景与方案总览
二 包安装加速
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = pypi.tuna.tsinghua.edu.cn
export http_proxy=http://127.0.0.1:7890
export https_proxy=http://127.0.0.1:7890
pip install -U pip
pip config list
三 Django 使用 Redis 缓存
sudo apt-get update
sudo apt-get install redis-server
pip install django-redis
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# 可按需开启: "PASSWORD": "yourpassword",
# "SOCKET_CONNECT_TIMEOUT": 5,
}
}
}
# 可选:将 session 存入 Redis
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
from django.core.cache import cache
def expensive_computation():
# ... 耗时计算
return result
key = "expensive_result"
result = cache.get(key)
if result is None:
result = expensive_computation()
cache.set(key, result, timeout=3600) # 1小时
四 HTTP 调用与反向代理缓存
pip install requests requests-cache
import requests_cache
requests_cache.install_cache('api_cache', expire_after=3600) # 缓存1小时
resp = requests.get('https://api.example.com/data')
print(resp.json())
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m;
server {
listen 80;
server_name example.com;
location /api/ {
proxy_pass https://backend_api/;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
}
}
五 使用 Memcached 做内存缓存
sudo apt-get install memcached
sudo systemctl enable --now memcached
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=False)
mc.set("some_key", "some_value", time=3600) # 1小时
value = mc.get("some_key")