Skip to content

Commit e35257c

Browse files
author
Simon Prickett
authored
Merge pull request #172 from redis/add-expire-#171
Add expire behavior
2 parents f024b39 + 93aa9f7 commit e35257c

File tree

4 files changed

+39
-0
lines changed

4 files changed

+39
-0
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,9 @@ print(andrew.pk)
119119
# We can save the model to Redis by calling `save()`:
120120
andrew.save()
121121

122+
# Expire the model after 2 mins (120 seconds)
123+
andrew.expire(120)
124+
122125
# To retrieve this customer with its primary key, we use `Customer.get()`:
123126
assert Customer.get(andrew.pk) == andrew
124127
```

aredis_om/model/model.py

+9
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,15 @@ async def update(self, **field_values):
11301130
async def save(self, pipeline: Optional[Pipeline] = None) -> "RedisModel":
11311131
raise NotImplementedError
11321132

1133+
async def expire(self, num_seconds: int, pipeline: Optional[Pipeline] = None):
1134+
if pipeline is None:
1135+
db = self.db()
1136+
else:
1137+
db = pipeline
1138+
1139+
# TODO: Wrap any Redis response errors in a custom exception?
1140+
await db.expire(self.make_primary_key(self.pk), num_seconds)
1141+
11331142
@validator("pk", always=True, allow_reuse=True)
11341143
def validate_pk(cls, v):
11351144
if not v:

docs/getting_started.md

+9
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,15 @@ andrew = Customer(
553553
andrew.save()
554554
```
555555

556+
## Expiring Models
557+
558+
We can expire an instance of a model using `expire`, and passing it the number of seconds after which we want the instance to expire in Redis:
559+
560+
```python
561+
# Expire Andrew in 2 minutes (120 seconds)
562+
andrew.expire(120)
563+
```
564+
556565
## Examining Your Data In Redis
557566

558567
You can view the data stored in Redis for any Redis OM model.

tests/test_hash_model.py

+18
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,24 @@ async def test_delete(m):
391391
assert response == 1
392392

393393

394+
@pytest.mark.asyncio
395+
async def test_expire(m):
396+
member = m.Member(
397+
first_name="Expire",
398+
last_name="Test",
399+
400+
join_date=today,
401+
age=93,
402+
bio="This is a test user for expiry",
403+
)
404+
405+
await member.save()
406+
await member.expire(60)
407+
408+
ttl = await m.Member.db().ttl(member.key())
409+
assert ttl > 0
410+
411+
394412
def test_raises_error_with_embedded_models(m):
395413
class Address(m.BaseHashModel):
396414
address_line_1: str

0 commit comments

Comments
 (0)