popoto.models.db_key¶
popoto.models.db_key
¶
Redis Key Generation and Management for Popoto Models.
This module provides the DB_key class, which is the foundation of Popoto's object identity system. Every Popoto model instance is uniquely identified by a Redis key, and DB_key handles the construction, parsing, and escaping of these keys.
Design Philosophy
Redis uses simple string keys, but Popoto models need hierarchical, structured identifiers that encode both the model type and the values of key fields. DB_key solves this by using a colon-delimited format:
ClassName:key1_value:key2_value:...
This design allows Redis SCAN and pattern matching to efficiently query all instances of a model class or filter by partial key values.
Key Escaping
Since colons are used as delimiters, any colon appearing in field values
must be escaped. DB_key also escapes Redis glob pattern characters to
prevent injection attacks or accidental pattern matching. The colon
escape sequence itself is self-escaping: a literal occurrence of the
escape sequence in the input is neutralized before colons are encoded,
so DB_key.unclean(DB_key.clean(v)) == v holds for every string
v, including strings that already contain the escape sequence.
Integration
DB_key is used throughout Popoto: - Model.db_key property generates the key for persistence - Query.get() uses DB_key to look up specific instances - ModelOptions stores the class-level key prefix (db_class_key) - Field indexes reference objects by their DB_key
DB_key
¶
Bases: list
A Redis key represented as a list of colon-separated parts.
The first element is the model class name, followed by the values of each
KeyField in definition order. The string form ClassName:val1:val2
is used as the actual Redis key. Special characters are escaped via
:meth:clean / :meth:unclean.
DB_key extends list to hold the "partials" (segments) of a Redis key. When converted to a string, these partials are joined with colons and properly escaped to form a valid Redis key.
This design allows keys to be constructed incrementally and composed from other DB_key instances, enabling patterns like:
class_key = DB_key("User")
instance_key = DB_key(class_key, user_id) # "User:123"
The list inheritance provides natural iteration over key segments, which is useful for extracting field values from stored keys.
Examples:
Source code in src/popoto/models/db_key.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
redis_key
property
¶
The colon-joined string used as the actual Redis key.
Alias for str(self) providing semantic clarity in Redis operations.
While DB_key can be converted to a string directly, this property makes code more readable when the key is being used specifically for Redis commands.
Returns:
| Type | Description |
|---|---|
|
The Redis key string representation. |
from_redis_key(redis_key)
classmethod
¶
Parse a ClassName:val1:val2 Redis key string into a DB_key.
This factory method is the inverse of str. It parses a colon-delimited Redis key back into its component partials, unescaping any special characters that were escaped during key construction.
This is essential for extracting field values from stored keys, particularly in Query operations that need to return KeyField values without fetching the full object from Redis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis_key
|
A Redis key as string or bytes (e.g., from SCAN). |
required |
Returns:
| Type | Description |
|---|---|
|
A new DB_key instance with unescaped partials. |
Examples:
Source code in src/popoto/models/db_key.py
clean(value)
classmethod
¶
Escape special Redis glob/key characters in value.
Redis keys can contain any bytes, but Popoto uses colons as delimiters and must also prevent accidental glob pattern interpretation. This method escapes, in order: 1. Forward slashes (/) -> doubled (//) as the escape character 2. Glob pattern chars ('?*^[]-) -> prefixed with / 3. Literal occurrences of COLON_ESCAPE ({:}) -> prefixed with / (self-escaping, so clean()'s own output is never mistaken for data by unclean()) 4. Colons (:) -> COLON_ESCAPE ({:})
The colon escaping uses an HTML-entity-inspired format rather than the slash prefix to make colons visually distinct, since they are the most structurally important character to escape.
The order is load-bearing: step 3 must run after step 1 (so the "/" it inserts is itself an escape character, not raw data) and before step 4 (so it only catches COLON_ESCAPE sequences that were already present in the input, never the one this call produces). This makes COLON_ESCAPE self-escaping, the same round-trip guarantee "/" already has.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
A raw string value to be used as a key segment. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The escaped string safe for use in Redis keys. Never contains |
str
|
a literal ":", so from_redis_key()'s split(":") stays |
str
|
unambiguous. |
Source code in src/popoto/models/db_key.py
unclean(value)
classmethod
¶
Reverse the escaping applied by :meth:clean.
This is the inverse of clean(), used when parsing stored Redis keys back into their original field values.
Unlike clean(), this is a single left-to-right scan rather than a sequential replace chain -- a sequential chain cannot distinguish a "/"-escaped COLON_ESCAPE token (data) from a COLON_ESCAPE token clean() itself produced (an escape), because the colon decode would have to run before slash unescaping either way.
The overwhelmingly common case -- a key part with no escapes at all -- takes a fast path first: if neither "/" nor COLON_ESCAPE appears anywhere in value, every scanner branch below would fall through to "emit the character as-is" for the whole string, so the scan is provably equivalent to returning value unchanged. This reduces that case to two C-level substring scans instead of a Python character loop, which matters because from_redis_key() calls unclean() once per key part on every query result.
When the fast path does not apply, the scan walks the string once:
- At a "/" whose following character is in ESCAPABLE: emit that
character literally and advance 2. This covers "//" -> "/",
"/
The ESCAPABLE guard on the "/" branch is deliberate, not incidental: a greedy branch that consumes any following character would widen the escape set on input clean() never produced (e.g. "/a" would decode to "a" instead of staying "/a"). Restricting to ESCAPABLE keeps this method byte-identical to the pre-fix implementation on every input clean() can produce, while also fixing the self-escaping bug on the inputs that exposed it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
An escaped key segment from a Redis key. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The original unescaped string value. |
Source code in src/popoto/models/db_key.py
exists()
¶
Return True if this key exists in Redis.
Provides a convenient way to verify object existence without fetching the full data. Useful for validation before operations that assume an object exists.
Returns:
| Type | Description |
|---|---|
|
True if a Redis key with this value exists, False otherwise. |
Source code in src/popoto/models/db_key.py
get_instance(model_class)
¶
Load and return a model instance from Redis for this key.
Fetches the hash stored at this key and deserializes it into a model instance. This method bridges the gap between a key (object identity) and the actual object (data).
The model_class parameter is required because DB_key itself does not store type information beyond the class name string in the first segment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Popoto Model class to instantiate. |
required |
Returns:
| Type | Description |
|---|---|
|
A model instance populated with data from Redis, or None |
|
|
if the key does not exist. |