在django中使用redis缓存接口数据,核心做法是安装并配置`django-redis`客户端,将django的缓存后端(caches)指向redis服务,然后在视图层通过`cache.get()`和`cache.set()`方法实现数据的读写与过期控制。具体操作需在`settings.py`中定义`location`为`redis://localhost:6379/0`,并在业务逻辑中判断缓存是否存在,若不存在则查询数据库并存入redis,从而减少数据库压力。

如何正确配置Django的缓存后端以连接Redis
正确配置的关键在于修改`settings.py`中的`CACHES`字典,指定`BACKEND`为`django_redis.cache.RedisCache`,并通过`LOCATION`参数指明Redis的连接地址。通常开发环境使用本地默认端口,生产环境则需确保网络可达及密码安全。配置完成后,Django会自动管理连接池,无需在视图中手动创建Redis客户端实例。

import redis
from django.conf import settings
def get_redis_client():
# 从Django设置中获取配置
cache_conf = settings.CACHES['default']
location = cache_conf['LOCATION']
# 解析 redis://host:port/db
if location.startswith('redis://'):
location = location[8:]
host_port_db = location.split('/')
host_port = host_port_db[0].split(':')
db = int(host_port_db[1]) if len(host_port_db) > 1 else 0
r = redis.Redis(
host=host_port[0],
port=int(host_port[1]),
db=db,
decode_responses=True
)
return r
# 测试连接
if __name__ == '__main__':
client = get_redis_client()
print(client.ping())
上述代码展示了如何从Django配置中提取Redis连接信息并建立独立连接,用于验证连通性或执行非Django标准的Redis操作。预期输出为`True`,表示连接成功。注意实际项目中应直接使用`django.core.cache`模块,而非手动管理连接。
如何在视图函数中实现缓存读写逻辑
在视图函数中实现缓存逻辑的标准模式是“先查缓存,未命中再查库,最后写缓存”。使用`django.core.cache.cache`对象调用`get(key)`检查数据,若返回`None`则执行数据库查询,随后用`set(key, value, timeout)`存入Redis。键名设计需唯一且包含版本或哈希信息以防冲突,超时时间根据业务数据更新频率设定。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

from django.core.cache import cache
from django.http import JsonResponse
from myapp.models import Article
import json
def article_detail(request, article_id):
cache_key = f'article_detail:{article_id}'
# 尝试从缓存获取
cached_data = cache.get(cache_key)
if cached_data:
return JsonResponse(cached_data)
# 缓存未命中,查询数据库
try:
article = Article.objects.get(id=article_id)
data = {
'id': article.id,
'title': article.title,
'content': article.content,
'author': article.author.username
}
# 存入缓存,过期时间300秒
cache.set(cache_key, data, timeout=300)
return JsonResponse(data)
except Article.DoesNotExist:
return JsonResponse({'error': 'Article not found'}, status=404)
该视图演示了完整的缓存读写流程。输入为`article_id`,若缓存命中直接返回JSON;若未命中则查库、序列化、写缓存并返回。预期结果是首次请求较慢但后续请求极快,且Redis中存储了对应的JSON字符串。需注意`cache.set`的第三个参数是过期时间(秒),可根据需求调整。
当数据库数据更新时如何清除相关缓存
当关联的数据库记录发生增删改时,必须主动清除对应缓存,否则用户将读到过期数据。最佳实践是在模型的`save()`或`delete()`信号处理器中,或者在视图的业务逻辑末尾,调用`cache.delete(key)`或`cache.delete_pattern(pattern)`来失效缓存。对于复杂关联,可使用命名空间或前缀批量清理。
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.core.cache import cache
from myapp.models import Article
def invalidate_article_cache(article_id):
key = f'article_detail:{article_id}'
cache.delete(key)
@receiver(post_save, sender=Article)
def handle_article_save(sender, instance, **kwargs):
invalidate_article_cache(instance.id)
@receiver(post_delete, sender=Article)
def handle_article_delete(sender, instance, **kwargs):
invalidate_article_cache(instance.id)
此段代码通过Django信号机制自动处理缓存失效。当`Article`模型保存或删除时,自动调用`invalidate_article_cache`删除Redis中对应的键。这确保了数据一致性,避免了手动在每个视图里添加删除逻辑的错误遗漏。预期行为是:任何对文章的修改都会导致下一次访问触发数据库查询并重新填充缓存。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










