Python Redis Module Skill 标志

Python Redis Module Skill

社区
jiushiwon
python-redis-module-skill

Python Redis 模块快速集成技能。面向已拥有 FastAPI 项目骨架的开发者,提供 Redis 缓存、Session 存储、分布式锁、限流、消息队列等能力的快速集成。触发词:"Python Redis"、"FastAPI Redis"、"Redis 集成"、"redis cache"、"redis session"、"redis lock"、"redis 限流"、"redis 消息队列"。

概览

发布者jiushiwon
代码仓库wg-skills
技能名称python-redis-module-skill
星标数
123
复刻数
38
附带文件
仅含指令
许可协议Apache-2.0
链接
  • Markdown 格式的指令

    模型按需加载的 SKILL.md 文件,因此只有在请求确实匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 jiushiwon 发布于 GitHub。请在安装前查看源内容。

安装

在 TypingMind 中安装 Python Redis Module Skill AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/jiushiwon/wg-skills/tree/main/vibeCoding/backend/python/fastapi-module/python-redis-module-skill
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/jiushiwon/wg-skills.git /tmp/wg-skills
mkdir -p .claude/skills
cp -r /tmp/wg-skills/vibeCoding/backend/python/fastapi-module/python-redis-module-skill .claude/skills/python-redis-module-skill
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Python Redis Module Skill,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Python Redis Module Skill。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Python Redis Module Skill 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Python Redis Module Skill

面向已有 FastAPI 项目的开发者,快速集成 Redis 能力。

能力清单

能力说明
缓存装饰器缓存、缓存更新、缓存删除
SessionRedis Session 共享
分布式锁基于 Redis 的分布式锁
限流基于 Redis 的接口限流
消息队列Redis Stream 消息发布/订阅
计数器分布式计数器

触发场景

用户说"帮我加 Redis"或"集成 Redis"时触发。

依赖配置

bash
pip install redis aioredis

默认方法封装

1. Redis 客户端

python
# redis_client.py
import redis
from typing import Optional

class RedisClient:
    def __init__(self, host: str = "localhost", port: int = 6379, password: Optional[str] = None, db: int = 0):
        self.client = redis.Redis(
            host=host,
            port=port,
            password=password,
            db=db,
            decode_responses=True
        )
    
    # 基础操作
    def get(self, key: str) -> Optional[str]:
        return self.client.get(key)
    
    def set(self, key: str, value: str, ex: Optional[int] = None) -> bool:
        return self.client.set(key, value, ex=ex)
    
    def delete(self, *keys: str) -> int:
        return self.client.delete(*keys)
    
    def exists(self, key: str) -> bool:
        return self.client.exists(key)
    
    def expire(self, key: str, seconds: int) -> bool:
        return self.client.expire(key, seconds)
    
    # 哈希操作
    def hget(self, name: str, key: str) -> Optional[str]:
        return self.client.hget(name, key)
    
    def hset(self, name: str, key: str, value: str) -> int:
        return self.client.hset(name, key, value)
    
    def hgetall(self, name: str) -> dict:
        return self.client.hgetall(name)
    
    # 列表操作
    def lpush(self, name: str, *values: str) -> int:
        return self.client.lpush(name, *values)
    
    def rpop(self, name: str) -> Optional[str]:
        return self.client.rpop(name)
    
    # 自增
    def incr(self, key: str, amount: int = 1) -> int:
        return self.client.incr(key, amount)
    
    # 分布式锁
    def lock(self, key: str, timeout: int = 30) -> bool:
        return self.client.set(f"lock:{key}", "1", nx=True, ex=timeout)
    
    def unlock(self, key: str) -> int:
        return self.client.delete(f"lock:{key}")

# 全局实例
redis_client = RedisClient()

2. 缓存装饰器

python
# cache.py
import json
import functools
from typing import Callable, Optional, Any

def cache(key_prefix: str, expire: int = 300):
    """缓存装饰器"""
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        async def wrapper(*args, **kwargs) -> Any:
            # 生成缓存 key
            cache_key = f"{key_prefix}:{':'.join(str(a) for a in args)}"
            
            # 尝试从缓存获取
            cached = redis_client.get(cache_key)
            if cached:
                return json.loads(cached)
            
            # 执行函数
            result = await func(*args, **kwargs)
            
            # 存入缓存
            redis_client.set(cache_key, json.dumps(result, ensure_ascii=False), ex=expire)
            return result
        return wrapper
    return decorator

# 使用示例
@cache("user:info", expire=600)
async def get_user(user_id: int):
    # 首次查询数据库,之后从缓存取
    return await db.query_user(user_id)

3. 分布式锁

python
# lock.py
import asyncio
from contextlib import asynccontextmanager
from typing import Optional

class RedisLock:
    def __init__(self, client: RedisClient):
        self.client = client
    
    @asynccontextmanager
    async def lock(self, key: str, timeout: int = 30, retry: int = 3, delay: float = 0.2):
        """分布式锁上下文管理器"""
        lock_key = f"lock:{key}"
        
        for _ in range(retry):
            if self.client.client.set(lock_key, "1", nx=True, ex=timeout):
                try:
                    yield True
                finally:
                    self.client.client.delete(lock_key)
                return
            await asyncio.sleep(delay)
        
        raise TimeoutError(f"获取锁 {key} 失败")

# 使用
lock = RedisLock(redis_client)
async with lock.lock("order:create"):
    # 临界区代码
    pass

4. 限流

python
# rate_limit.py
import time
from typing import Optional

class RateLimiter:
    def __init__(self, client: RedisClient):
        self.client = client
    
    def try_acquire(self, key: str, max_requests: int, window_seconds: int = 60) -> bool:
        """滑动窗口限流"""
        now = time.time()
        window_key = f"ratelimit:{key}"
        
        # 移除过期的请求记录
        self.client.client.zremrangebyscore(window_key, 0, now - window_seconds)
        
        # 当前请求数
        current = self.client.client.zcard(window_key)
        
        if current >= max_requests:
            return False
        
        # 添加当前请求
        self.client.client.zadd(window_key, {str(now): now})
        self.client.client.expire(window_key, window_seconds)
        return True

# 使用
limiter = RateLimiter(redis_client)

async def check_rate_limit(request_id: str) -> bool:
    if not limiter.try_acquire(f"api:{request_id}", 100, 60):
        raise Exception("请求过于频繁")
    return True

5. 消息队列(Stream)

python
# mq.py
import json
from typing import Callable, Dict, Any, Optional

class RedisStream:
    def __init__(self, client: RedisClient):
        self.client = client
    
    def publish(self, stream: str, data: Dict[str, Any]) -> str:
        """发布消息"""
        return self.client.client.xadd(stream, data)
    
    def subscribe(self, stream: str, group: str, consumer: str, count: int = 10, block: int = 5000):
        """订阅消息"""
        while True:
            messages = self.client.client.xread(
                {stream: "0"},
                count=count,
                block=block
            )
            if messages:
                for stream_name, msgs in messages:
                    for msg_id, msg_data in msgs:
                        yield msg_id, msg_data
                        # 确认消息
                        self.client.client.xack(stream, group, msg_id)

# 生产者
stream = RedisStream(redis_client)
stream.publish("notifications", {"user_id": "123", "message": "hello"})

# 消费者
async def consume_messages():
    async for msg_id, msg in stream.subscribe("notifications", "my-group", "consumer-1"):
        print(f"收到消息: {msg}")

配置模板

.env

env
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DATABASE=0

config.py

python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    redis_host: str = "localhost"
    redis_port: int = 6379
    redis_password: str = ""
    redis_database: int = 0

settings = Settings()

不做

  • 不负责安装 Redis(用户自行安装或使用 Docker)
  • 不处理 Redis 集群配置(单节点为主)
  • 不提供数据迁移工具
  • 不处理哨兵/主从配置

常见问题

Python Redis Module Skill AI 技能有什么作用?

Python Redis 模块快速集成技能。面向已拥有 FastAPI 项目骨架的开发者,提供 Redis 缓存、Session 存储、分布式锁、限流、消息队列等能力的快速集成。触发词:"Python Redis"、"FastAPI Redis"、"Redis 集成"、"redis cache"、"redis session"、"redis lock"、"redis 限流"、"redis 消息队列"。

为什么在 TypingMind 中使用 Python Redis Module Skill?

因为您只需安装一次,就能搭配任何模型使用。Python Redis Module Skill 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型,甚至可以在聊天中途切换模型,而不会影响技能正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Python Redis Module Skill?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/jiushiwon/wg-skills/tree/main/vibeCoding/backend/python/fastapi-module/python-redis-module-skill。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Python Redis Module Skill?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Python Redis Module Skill 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Python Redis Module Skill 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Python Redis Module Skill AI 技能免费吗?

是的。该技能源自 jiushiwon 在 GitHub 上以 Apache-2.0 许可证发布的项目。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇