Redis的对象映射及其他功能。
项目描述
Redis和Python的对象映射及其他功能
Redis OM Python 使您在Python应用程序中轻松建模Redis数据。
Redis OM .NET | Redis OM Node.js | Redis OM Spring | Redis OM Python
目录
span
💡 为什么选择Redis OM?
Redis OM提供了高级抽象,使得现代Python应用程序轻松地在Redis中建模和查询数据。
此预览版本包含以下功能
- Redis对象的声明式对象映射
- 声明式二级索引生成
- 查询Redis的流畅API
💻 安装
使用pip
、Poetry或Pipenv安装非常简单。
# With pip
$ pip install redis-om
# Or, using Poetry
$ poetry add redis-om
🏁 入门
启动Redis
在编写任何代码之前,您需要一个具有适当Redis模块的Redis实例!获取此实例的最快方式是使用Docker
docker run -p 6379:6379 -p 8001:8001 redis/redis-stack
这启动了redis-stack,这是Redis的扩展,它向Redis添加了各种现代数据结构。您还会注意到,如果您打开http://localhost:8001,您将能够访问redis-insight GUI,这是一个您可以用来可视化并操作Redis中数据的GUI。
📇 建模您的数据
Redis OM包含强大的声明式模型,为您提供数据验证、序列化和持久化到Redis的功能。
请查看以下使用Redis OM建模客户数据的示例。首先,我们创建一个Customer
模型
import datetime
from typing import Optional
from pydantic import EmailStr
from redis_om import HashModel
class Customer(HashModel):
first_name: str
last_name: str
email: EmailStr
join_date: datetime.date
age: int
bio: Optional[str] = None
现在我们有了Customer
模型,让我们使用它将客户数据保存到Redis中。
import datetime
from typing import Optional
from pydantic import EmailStr
from redis_om import HashModel
class Customer(HashModel):
first_name: str
last_name: str
email: EmailStr
join_date: datetime.date
age: int
bio: Optional[str] = None
# First, we create a new `Customer` object:
andrew = Customer(
first_name="Andrew",
last_name="Brookins",
email="andrew.brookins@example.com",
join_date=datetime.date.today(),
age=38,
bio="Python developer, works at Redis, Inc."
)
# The model generates a globally unique primary key automatically
# without needing to talk to Redis.
print(andrew.pk)
# > "01FJM6PH661HCNNRC884H6K30C"
# We can save the model to Redis by calling `save()`:
andrew.save()
# Expire the model after 2 mins (120 seconds)
andrew.expire(120)
# To retrieve this customer with its primary key, we use `Customer.get()`:
assert Customer.get(andrew.pk) == andrew
想要了解更多吗?查看入门指南。
或者,继续阅读以了解Redis OM如何使数据验证变得容易。
✓ 使用您的模型验证数据
Redis OM使用Pydantic根据您分配给模型类中字段的类型注解来验证数据。
此验证确保像first_name
这样的字段,该字段由Customer
模型标记为str
,始终是字符串。但每个Redis OM模型也是一个Pydantic模型,因此您可以使用Pydantic验证器如EmailStr
、Pattern
等进行复杂验证!
例如,由于我们为email
字段使用了EmailStr
类型,如果尝试创建一个包含无效电子邮件地址的Customer
,我们将得到验证错误
import datetime
from typing import Optional
from pydantic import EmailStr, ValidationError
from redis_om import HashModel
class Customer(HashModel):
first_name: str
last_name: str
email: EmailStr
join_date: datetime.date
age: int
bio: Optional[str] = None
try:
Customer(
first_name="Andrew",
last_name="Brookins",
email="Not an email address!",
join_date=datetime.date.today(),
age=38,
bio="Python developer, works at Redis, Inc."
)
except ValidationError as e:
print(e)
"""
pydantic.error_wrappers.ValidationError: 1 validation error for Customer
email
value is not a valid email address (type=value_error.email)
"""
任何现有的Pydantic验证器都可以作为Redis OM模型的插入类型注解使用。您还可以编写任意复杂的自定义验证!
要了解更多信息,请参阅数据验证文档。
🔎 丰富查询和嵌入式模型
数据建模、验证以及将模型保存到Redis都在运行Redis的方式无关。
接下来,我们将向您展示当RediSearch和RedisJSON模块安装到您的Redis部署中,或者您正在使用Redis Enterprise时,Redis OM提供的强大查询表达式和嵌入式模型。
提示:等等,什么是Redis模块?如果您不熟悉Redis模块,请参阅此README的那么,您如何获取RediSearch和RedisJSON?部分。
查询中
Redis OM附带了一个丰富的查询语言,允许您使用Python表达式查询Redis。
为了说明这是如何工作的,我们将对之前定义的Customer
模型进行一些小的更改。我们将添加Field(index=True)
来告诉Redis OM我们希望对last_name
和age
字段进行索引
import datetime
from typing import Optional
from pydantic import EmailStr
from redis_om import (
Field,
HashModel,
Migrator
)
class Customer(HashModel):
first_name: str
last_name: str = Field(index=True)
email: EmailStr
join_date: datetime.date
age: int = Field(index=True)
bio: Optional[str] = None
# Now, if we use this model with a Redis deployment that has the
# RediSearch module installed, we can run queries like the following.
# Before running queries, we need to run migrations to set up the
# indexes that Redis OM will use. You can also use the `migrate`
# CLI tool for this!
Migrator().run()
# Find all customers with the last name "Brookins"
Customer.find(Customer.last_name == "Brookins").all()
# Find all customers that do NOT have the last name "Brookins"
Customer.find(Customer.last_name != "Brookins").all()
# Find all customers whose last name is "Brookins" OR whose age is
# 100 AND whose last name is "Smith"
Customer.find((Customer.last_name == "Brookins") | (
Customer.age == 100
) & (Customer.last_name == "Smith")).all()
这些查询以及其他更多功能都是可能的,因为Redis OM会自动为您管理索引。
使用此索引的查询具有灵感来自Django ORM、SQLAlchemy和Peewee的丰富表达式语法。我们相信您会喜欢它!
注意:索引功能仅适用于存储在Redis逻辑数据库0中的数据。如果您在连接Redis时使用不同的数据库编号,则在运行迁移器时可能会引发MigrationError
。
嵌入式模型
Redis OM可以像任何文档数据库一样存储和查询嵌套模型,同时提供Redis的速度和功能。让我们看看它是如何工作的。
在下一个示例中,我们将定义一个新的Address
模型,并将其嵌入到Customer
模型中。
import datetime
from typing import Optional
from redis_om import (
EmbeddedJsonModel,
JsonModel,
Field,
Migrator,
)
class Address(EmbeddedJsonModel):
address_line_1: str
address_line_2: Optional[str] = None
city: str = Field(index=True)
state: str = Field(index=True)
country: str
postal_code: str = Field(index=True)
class Customer(JsonModel):
first_name: str = Field(index=True)
last_name: str = Field(index=True)
email: str = Field(index=True)
join_date: datetime.date
age: int = Field(index=True)
bio: Optional[str] = Field(index=True, full_text_search=True,
default="")
# Creates an embedded model.
address: Address
# With these two models and a Redis deployment with the RedisJSON
# module installed, we can run queries like the following.
# Before running queries, we need to run migrations to set up the
# indexes that Redis OM will use. You can also use the `migrate`
# CLI tool for this!
Migrator().run()
# Find all customers who live in San Antonio, TX
Customer.find(Customer.address.city == "San Antonio",
Customer.address.state == "TX")
调用其他Redis命令
有时您需要直接运行Redis命令。Redis OM通过模型类的db
方法支持此功能。这返回一个连接的Redis客户端实例,该实例公开了以Redis命令命名的函数。例如,让我们执行一些基本集合操作
from redis_om import HashModel
class Demo(HashModel):
some_field: str
redis_conn = Demo.db()
redis_conn.sadd("myset", "a", "b", "c", "d")
# Prints False
print(redis_conn.sismember("myset", "e"))
# Prints True
print(redis_conn.sismember("myset", "b"))
每个命令函数期望的参数可以在redis.io上该命令页面上找到。
如果您不想从模型类中获取Redis连接,您也可以使用get_redis_connection
from redis_om import get_redis_connection
redis_conn = get_redis_connection()
redis_conn.set("hello", "world")
📚 文档
Redis OM文档可在此处找到。
⛏️ 故障排除
如果您遇到问题或有任何疑问,我们在这里为您提供帮助!
请访问Redis Discord服务器或在GitHub上创建问题。
✨ 那么,您如何获取RediSearch和RedisJSON呢?
Redis OM的一些高级功能依赖于两个可用的Redis模块的核心功能:[RediSearch](https://redis.ac.cn/docs/stack/search/)和[RedisJSON](https://redis.ac.cn/docs/stack/json/)。
您可以在自己的Redis部署中运行这些模块,或者使用包括这两个模块的Redis Enterprise。
要了解更多信息,请阅读我们的文档。
❤️ 贡献
我们期待您的贡献!
错误报告在项目这个阶段特别有帮助。[在GitHub上打开错误报告](https://github.com/redis/redis-om-python/issues/new)
您还可以贡献文档——或者只是让我们知道哪些地方需要更多细节。[在GitHub上创建问题](https://github.com/redis/redis-om-python/issues/new)开始。
📝 许可证
Redis OM使用MIT许可证。
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。
源分布
构建分布
redis_om-0.3.2.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 28e69e1228ec1c2c3ff4fd051788cd391cc673c7187f82159816e70f5dcf7d2e |
|
MD5 | 780be33948ffbcc9437964dc313bc46f |
|
BLAKE2b-256 | 39aee2ad293032fa3b19380700503d9ee2cf400eb9a400ffc7309f53be09db70 |
redis_om-0.3.2-py3-none-any.whl 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 37c2075f150509ef3f9274903000d0eeca710af2aa11877dac0da0c7456d70b8 |
|
MD5 | e7f28e3e0bc4c7ffbcf2b835faa55f67 |
|
BLAKE2b-256 | 6a229d4950ea12d5d2ab78701dc2225a7c3615d51438dffc424e09144cfa7f40 |