Skip to content

Commit 979e74b

Browse files
authored
Update docs to Material theme and 1.0 compatibility (#778)
* Update docs to Material theme and 1.0 compatibility - Switch to Material for MkDocs theme with Redis branding - Combine connections.md and redis_modules.md into redis_setup.md - Recommend Redis 8 over Redis Stack - Update all code examples for 1.0: - Add model-level index=True to indexed models - Update Pydantic validators to v2 syntax - Update error message formats to Pydantic v2 style - Replace @app.on_event with lifespan pattern in FastAPI examples - Replace Migrator().run() with om migrate CLI reference * Link to hosted documentation site in README * Add RedisInsight to spellcheck wordlist
1 parent 5c1dbc7 commit 979e74b

13 files changed

Lines changed: 476 additions & 246 deletions

.github/wordlist.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ README.md
2626
Redi
2727
RediSearch
2828
RediSearch
29+
RedisInsight
2930
RedisJSON
3031
SQLAlchemy
3132
SSL

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ redis_conn.set("hello", "world")
352352

353353
## 📚 Documentation
354354

355-
The Redis OM documentation is available [here](docs/index.md).
355+
The Redis OM documentation is available at **[redis.github.io/redis-om-python](https://redis.github.io/redis-om-python/)**.
356356

357357
## ⛏️ Troubleshooting
358358

@@ -366,7 +366,7 @@ Some advanced features of Redis OM rely on core features from two source availab
366366

367367
You can run these modules in your self-hosted Redis deployment, or you can use [Redis Enterprise][redis-enterprise-url], which includes both modules.
368368

369-
To learn more, read [our documentation](docs/redis_modules.md).
369+
To learn more, read [our documentation](docs/redis_setup.md).
370370

371371
## Connecting to Azure Managed Redis with EntraID
372372

docs/connections.md

Lines changed: 0 additions & 100 deletions
This file was deleted.

docs/fastapi_integration.md

Lines changed: 40 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,26 @@ class Customer(HashModel):
6767
bio: Optional[str]
6868

6969

70-
app = FastAPI()
70+
from contextlib import asynccontextmanager
71+
72+
73+
@asynccontextmanager
74+
async def lifespan(app: FastAPI):
75+
# Startup: Initialize cache and Redis OM connection
76+
r = redis.asyncio.from_url(REDIS_CACHE_URL, encoding="utf8",
77+
decode_responses=True)
78+
FastAPICache.init(RedisBackend(r), prefix="fastapi-cache")
79+
80+
# You can set the Redis OM URL using the REDIS_OM_URL environment
81+
# variable, or by manually creating the connection using your model's
82+
# Meta object.
83+
Customer.Meta.database = get_redis_connection(url=REDIS_DATA_URL,
84+
decode_responses=True)
85+
yield
86+
# Shutdown: cleanup if needed
87+
88+
89+
app = FastAPI(lifespan=lifespan)
7190

7291

7392
@app.post("/customer")
@@ -90,19 +109,6 @@ async def get_customer(pk: str, request: Request, response: Response):
90109
return Customer.get(pk)
91110
except NotFoundError:
92111
raise HTTPException(status_code=404, detail="Customer not found")
93-
94-
95-
@app.on_event("startup")
96-
async def startup():
97-
r = redis.asyncio.from_url(REDIS_CACHE_URL, encoding="utf8",
98-
decode_responses=True)
99-
FastAPICache.init(RedisBackend(r), prefix="fastapi-cache")
100-
101-
# You can set the Redis OM URL using the REDIS_OM_URL environment
102-
# variable, or by manually creating the connection using your model's
103-
# Meta object.
104-
Customer.Meta.database = get_redis_connection(url=REDIS_DATA_URL,
105-
decode_responses=True)
106112
```
107113

108114
## Testing the app
@@ -179,7 +185,26 @@ class Customer(HashModel):
179185
bio: Optional[str]
180186

181187

182-
app = FastAPI()
188+
from contextlib import asynccontextmanager
189+
190+
191+
@asynccontextmanager
192+
async def lifespan(app: FastAPI):
193+
# Startup: Initialize cache and Redis OM connection
194+
r = redis.asyncio.from_url(REDIS_CACHE_URL, encoding="utf8",
195+
decode_responses=True)
196+
FastAPICache.init(RedisBackend(r), prefix="fastapi-cache")
197+
198+
# You can set the Redis OM URL using the REDIS_OM_URL environment
199+
# variable, or by manually creating the connection using your model's
200+
# Meta object.
201+
Customer.Meta.database = get_redis_connection(url=REDIS_DATA_URL,
202+
decode_responses=True)
203+
yield
204+
# Shutdown: cleanup if needed
205+
206+
207+
app = FastAPI(lifespan=lifespan)
183208

184209

185210
@app.post("/customer")
@@ -202,19 +227,6 @@ async def get_customer(pk: str, request: Request, response: Response):
202227
return await Customer.get(pk) # <- And, finally, one more await!
203228
except NotFoundError:
204229
raise HTTPException(status_code=404, detail="Customer not found")
205-
206-
207-
@app.on_event("startup")
208-
async def startup():
209-
r = redis.asyncio.from_url(REDIS_CACHE_URL, encoding="utf8",
210-
decode_responses=True)
211-
FastAPICache.init(RedisBackend(r), prefix="fastapi-cache")
212-
213-
# You can set the Redis OM URL using the REDIS_OM_URL environment
214-
# variable, or by manually creating the connection using your model's
215-
# Meta object.
216-
Customer.Meta.database = get_redis_connection(url=REDIS_DATA_URL,
217-
decode_responses=True)
218230
```
219231

220232
**NOTE:** The modules `redis_om` and `aredis_om` are identical in almost every

docs/getting_started.md

Lines changed: 42 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,24 @@ The command to start Redis with Docker depends on the image you've chosen to use
8181

8282
**TIP:** The `-d` option in these examples runs Redis in the background, while `-p 6379:6379` makes Redis reachable at port 6379 on your localhost.
8383

84-
#### Docker with the `redismod` image (recommended)
84+
#### Docker with Redis 8 (recommended)
8585

86-
$ docker run -d -p 6379:6379 redislabs/redismod
86+
$ docker run -d -p 6379:6379 redis:8
8787

88-
### Docker with the `redis` image
88+
Redis 8 includes the Search and JSON capabilities needed for full Redis OM functionality.
89+
90+
#### Docker with Redis Stack
91+
92+
$ docker run -d -p 6379:6379 redis/redis-stack
93+
94+
Redis Stack also includes the Search and JSON capabilities.
95+
96+
#### Docker with the basic `redis` image
8997

9098
$ docker run -d -p 6379:6379 redis
9199

100+
**NOTE:** The basic Redis image does not include Search and JSON capabilities. You can still use Redis OM for data modeling and persistence, but `JsonModel` and the `find()` query interface won't work.
101+
92102
## Installing Redis OM
93103

94104
The recommended way to install Redis OM is with [Poetry](https://python-poetry.org/docs/). You can install Redis OM using Poetry with the following command:
@@ -239,9 +249,9 @@ try:
239249
except ValidationError as e:
240250
print(e)
241251
"""
242-
ValidationError: 1 validation error for Customer
252+
1 validation error for Customer
243253
bio
244-
field required (type=value_error.missing)
254+
Field required [type=missing, input_value={'first_name': 'Andrew',..._date': datetime.date...}, input_type=dict]
245255
"""
246256
```
247257

@@ -389,9 +399,9 @@ try:
389399
except ValidationError as e:
390400
print(e)
391401
"""
392-
pydantic.error_wrappers.ValidationError: 1 validation error for Customer
402+
1 validation error for Customer
393403
join_date
394-
invalid date format (type=value_error.date)
404+
Input should be a valid date or datetime [type=date_from_datetime_parsing, ...]
395405
"""
396406
```
397407

@@ -471,9 +481,9 @@ try:
471481
except ValidationError as e:
472482
print(e)
473483
"""
474-
pydantic.error_wrappers.ValidationError: 1 validation error for Customer
484+
1 validation error for Customer
475485
age
476-
Value is not a valid integer (type=type_error.integer)
486+
Input should be a valid integer [type=int_type, ...]
477487
"""
478488
```
479489

@@ -487,13 +497,22 @@ from pydantic import ValidationError
487497
from redis_om import HashModel
488498

489499

500+
from typing import Annotated, Any
501+
from pydantic import GetCoreSchemaHandler
502+
from pydantic_core import CoreSchema, core_schema
503+
504+
490505
class StrictDate(datetime.date):
506+
"""A strict date type that doesn't allow string coercion."""
507+
491508
@classmethod
492-
def __get_validators__(cls) -> 'CallableGenerator':
493-
yield cls.validate
509+
def __get_pydantic_core_schema__(
510+
cls, source_type: Any, handler: GetCoreSchemaHandler
511+
) -> CoreSchema:
512+
return core_schema.no_info_plain_validator_function(cls.validate)
494513

495514
@classmethod
496-
def validate(cls, value: datetime.date, **kwargs) -> datetime.date:
515+
def validate(cls, value: Any) -> datetime.date:
497516
if not isinstance(value, datetime.date):
498517
raise ValueError("Value must be a datetime.date object")
499518
return value
@@ -516,14 +535,14 @@ try:
516535
last_name="Brookins",
517536
email="a@example.com",
518537
join_date="2020-01-02", # <- A string shouldn't work now!
519-
age="38"
538+
age=38
520539
)
521540
except ValidationError as e:
522541
print(e)
523542
"""
524-
pydantic.error_wrappers.ValidationError: 1 validation error for Customer
543+
1 validation error for Customer
525544
join_date
526-
Value must be a datetime.date object (type=value_error)
545+
Value error, Value must be a datetime.date object [type=value_error, ...]
527546
"""
528547
```
529548

@@ -670,11 +689,10 @@ from pydantic import EmailStr
670689
from redis_om import (
671690
Field,
672691
HashModel,
673-
Migrator
674692
)
675693

676694

677-
class Customer(HashModel):
695+
class Customer(HashModel, index=True):
678696
first_name: str
679697
last_name: str = Field(index=True)
680698
email: EmailStr
@@ -687,9 +705,8 @@ class Customer(HashModel):
687705
# RediSearch module installed, we can run queries like the following.
688706

689707
# Before running queries, we need to run migrations to set up the
690-
# indexes that Redis OM will use. You can also use the `om migrate`
691-
# CLI tool for this!
692-
Migrator().run()
708+
# indexes that Redis OM will use. Run the `om migrate` CLI tool:
709+
# $ om migrate
693710

694711
# Find all customers with the last name "Brookins"
695712
Customer.find(Customer.last_name == "Brookins").all()
@@ -710,16 +727,14 @@ For historical reasons, saving and querying Boolean values is not supported in `
710727
you may store and query Boolean values using the `==` syntax:
711728

712729
```python
713-
from redis_om import (
714-
Field,
715-
JsonModel,
716-
Migrator
717-
)
730+
from redis_om import Field, JsonModel
731+
718732

719-
class Demo(JsonModel):
733+
class Demo(JsonModel, index=True):
720734
b: bool = Field(index=True)
721735

722-
Migrator().run()
736+
737+
# Run migrations first with: om migrate
723738
d = Demo(b=True)
724739
d.save()
725740
res = Demo.find(Demo.b == True)

0 commit comments

Comments
 (0)