Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions docs/examples/pipeline_examples.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,67 @@
"pipe.set(\"a\", \"a value\").set(\"b\", \"b value\").get(\"a\").execute()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's a slightly more advanced example for chaining complex operations using the builder pattern."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from dataclasses import dataclass\n",
"from typing import Optional\n",
"\n",
"@dataclass\n",
"class User:\n",
" email: str\n",
" username: Optional[str] = None\n",
"\n",
"@dataclass\n",
"class Post:\n",
" title: str\n",
" body: str\n",
" author: Optional[str] = None\n",
"\n",
"class RedisRepository:\n",
" def __init__(self):\n",
" self.pipeline = r.pipeline()\n",
"\n",
" def add_user(self, user: User):\n",
" if not user.username:\n",
" user.username = user.email.split(\"@\")[0]\n",
" self.pipeline.hset(f\"user:{user.username}\", mapping={\"username\": user.username, \"email\": user.email})\n",
" return self\n",
" \n",
" def add_post(self, post: Post):\n",
" self.pipeline.hset(f\"post:#{post.title}#\", mapping={\"title\": post.title, \"body\": post.body, \"author\": post.author})\n",
" if post.author:\n",
" self.pipeline.sadd(f\"user:{post.author}:posts\", f\"post:#{post.title}#\")\n",
" return self\n",
"\n",
" def add_follow(self, follower: str, following: str):\n",
" self.pipeline.sadd(f\"user:{follower}:following\", following)\n",
" self.pipeline.sadd(f\"user:{following}:followers\", follower)\n",
" return self\n",
"\n",
" def execute(self):\n",
" return self.pipeline.execute()\n",
"\n",
"pipe = RedisRepository()\n",
"results = (pipe\n",
" .add_user(User(email=\"[email protected]\"))\n",
" .add_user(User(email=\"[email protected]\"))\n",
" .add_follow(\"alice\", \"bob\")\n",
" .add_post(Post(title=\"Hello World\", body=\"I'm using Redis!\", author=\"alice\"))\n",
" .execute()\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down