首页主机资讯Ubuntu Python配置中如何使用缓存

Ubuntu Python配置中如何使用缓存

时间2026-01-20 06:48:03发布访客分类主机资讯浏览694
导读:Ubuntu 下 Python 缓存使用指南 一 场景与方案总览 包安装加速:使用 pip 缓存与镜像源,显著缩短依赖安装时间。 应用数据缓存:在 Django 中使用 Redis 作为缓存后端,适合视图、查询结果、会话等高并发读场景。...

Ubuntu 下 Python 缓存使用指南

一 场景与方案总览

  • 包安装加速:使用 pip 缓存镜像源,显著缩短依赖安装时间。
  • 应用数据缓存:在 Django 中使用 Redis 作为缓存后端,适合视图、查询结果、会话等高并发读场景。
  • HTTP 调用缓存:对外部 API 使用 requests-cache 或将 Nginx 作为反向代理进行响应缓存。
  • 内存键值缓存:使用 Memcached 做进程外共享缓存,适合简单 KV、计数器等。

二 包安装加速

  • 配置 pip 镜像源(示例为清华源),创建或编辑配置文件 ~/.pip/pip.conf
    [global]
    index-url = https://pypi.tuna.tsinghua.edu.cn/simple
    trusted-host = pypi.tuna.tsinghua.edu.cn
    
  • 启用 HTTP 代理(如需要):
    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
    
  • 说明:新版 pip 默认启用下载缓存目录(无需再设置环境变量),命中缓存将直接复用本地包文件,提高重复安装速度。

三 Django 使用 Redis 缓存

  • 安装组件(Ubuntu):
    sudo apt-get update
    sudo apt-get install redis-server
    pip install django-redis
    
  • 配置 settings.py
    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"
    
  • 使用示例(函数/查询缓存,TTL 3600 秒):
    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小时
    
  • 要点:django-redis 提供与 Django 缓存 API 的无缝集成,支持 Redis 的高可用与可扩展性,适合生产环境。

四 HTTP 调用与反向代理缓存

  • 使用 requests-cache 缓存 API 响应(示例 3600 秒):
    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())
    
  • 使用 Nginx 作为反向代理缓存(示例配置片段):
    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;
    
            }
    
        }
    
    }
        
    
  • 说明:前者在 Python 进程内透明缓存,后者在 网关层统一缓存,适合降低后端负载与提升响应速度。

五 使用 Memcached 做内存缓存

  • 安装与启动(Ubuntu):
    sudo apt-get install memcached
    sudo systemctl enable --now memcached
    
  • Python 客户端示例(使用 python-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")
    
  • 要点:Memcached 是分布式内存对象缓存系统,适合简单 KV、计数器、会话存储等;在生产中常配合应用服务器多实例共享热点数据。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Ubuntu Python配置中如何使用缓存
本文地址: https://pptw.com/jishu/786798.html
Ubuntu Python配置中如何优化内存使用 如何在Ubuntu上配置Python并发处理

游客 回复需填写必要信息