Python Redis Module Skill logo

Python Redis Module Skill

Community
jiushiwon
python-redis-module-skill

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

Overview

Publisherjiushiwon
Repositorywg-skills
Skill namepython-redis-module-skill
Stars
123
Forks
38
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by jiushiwon on GitHub. Read the source before you install it.

Installation

Install the Python Redis Module Skill AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/jiushiwon/wg-skills/tree/main/vibeCoding/backend/python/fastapi-module/python-redis-module-skill
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Python Redis Module Skill in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Python Redis Module Skill on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Python Redis Module Skill is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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 集群配置(单节点为主)
  • 不提供数据迁移工具
  • 不处理哨兵/主从配置

Frequently asked questions

What does the Python Redis Module Skill AI skill do?

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

Why use Python Redis Module Skill on TypingMind?

Because you install it once and use it with any model. Python Redis Module Skill is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Python Redis Module Skill in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/jiushiwon/wg-skills/tree/main/vibeCoding/backend/python/fastapi-module/python-redis-module-skill. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Python Redis Module Skill?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Python Redis Module Skill?

As many as you like. As long as a model supports skills, you can use Python Redis Module Skill with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Python Redis Module Skill AI skill free?

Yes. It is published on GitHub by jiushiwon under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇