> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dify.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 持久化存储

> 使用内置的键值存储在插件的多次交互间保存数据

> 本文档由 AI 自动翻译。如有任何不准确之处，请参考 [英文原版](/en/develop-plugin/features-and-specs/plugin-types/persistent-storage-kv)。

## 概述

大多数插件工具和端点以无状态的单轮交互模型运行：

1. 接收请求
2. 处理数据
3. 返回响应
4. 结束交互

然而，许多实际应用需要在多次交互中维护状态。这正是 **持久化存储** 的关键所在。

<Info>
  持久化存储让插件在同一工作空间内跨交互保存数据，从而实现有状态应用和记忆功能。
</Info>

Dify 目前为插件提供键值（KV）存储系统；后续会根据开发者需求提供更灵活、更强大的存储接口。

## 访问存储

所有存储操作都通过插件会话中可用的 `storage` 对象执行：

```python theme={null}
# Access the storage interface
storage = self.session.storage
```

## 存储操作

### 存储数据

使用 `set` 方法存储数据：

```python theme={null}
def set(self, key: str, val: bytes) -> None:
    """
    Store data in persistent storage
    
    Parameters:
        key: Unique identifier for your data
        val: Binary data to store (bytes)
    """
    pass
```

<Warning>
  值必须是 `bytes` 格式。这提供了存储各种类型数据的灵活性，包括文件。
</Warning>

#### 示例：存储不同数据类型

```python theme={null}
# String data (must convert to bytes)
storage.set("user_name", "John Doe".encode('utf-8'))

# JSON data
import json
user_data = {"name": "John", "age": 30, "preferences": ["AI", "NLP"]}
storage.set("user_data", json.dumps(user_data).encode('utf-8'))

# File data
with open("image.jpg", "rb") as f:
    image_data = f.read()
    storage.set("profile_image", image_data)
```

### 检索数据

使用 `get` 方法检索存储的数据：

```python theme={null}
def get(self, key: str) -> bytes:
    """
    Retrieve data from persistent storage
    
    Parameters:
        key: Unique identifier for your data
        
    Returns:
        The stored data as bytes, or None if key doesn't exist
    """
    pass
```

#### 示例：检索和转换数据

```python theme={null}
# Retrieving string data
name_bytes = storage.get("user_name")
if name_bytes:
    name = name_bytes.decode('utf-8')
    print(f"Retrieved name: {name}")

# Retrieving JSON data
import json
user_data_bytes = storage.get("user_data")
if user_data_bytes:
    user_data = json.loads(user_data_bytes.decode('utf-8'))
    print(f"User preferences: {user_data['preferences']}")
```

### 删除数据

使用 `delete` 方法删除存储的数据：

```python theme={null}
def delete(self, key: str) -> None:
    """
    Delete data from persistent storage
    
    Parameters:
        key: Unique identifier for the data to delete
    """
    pass
```

## 最佳实践

<CardGroup cols={2}>
  <Card title="使用描述性键名" icon="key">
    为键创建一致的命名方案，以避免冲突并使代码更易于维护。
  </Card>

  <Card title="处理缺失的键" icon="triangle-exclamation">
    在处理数据之前始终检查数据是否存在，因为键可能不存在。
  </Card>

  <Card title="序列化复杂数据" icon="code">
    在存储之前将复杂对象转换为 JSON 或其他序列化格式。
  </Card>

  <Card title="实现错误处理" icon="shield">
    将存储操作包装在 try/except 块中，以优雅地处理潜在错误。
  </Card>
</CardGroup>

## 常见用例

* **用户偏好**：在会话之间存储用户设置和偏好。
* **对话历史**：维护先前对话的上下文。
* **API 令牌**：安全存储认证令牌。
* **缓存数据**：存储频繁访问的数据以减少 API 调用。
* **文件存储**：存储用户上传的文件或生成的内容。
