Get cache values in sorted order; see :py:meth:`.SQLiteCache.sorted` for usage details
(
self,
key: str = 'expires',
reversed: bool = False,
limit: Optional[int] = None,
expired: bool = True,
)
| 413 | return page_count * page_size |
| 414 | |
| 415 | def sorted( |
| 416 | self, |
| 417 | key: str = 'expires', |
| 418 | reversed: bool = False, |
| 419 | limit: Optional[int] = None, |
| 420 | expired: bool = True, |
| 421 | ) -> Iterator[CachedResponse]: |
| 422 | """Get cache values in sorted order; see :py:meth:`.SQLiteCache.sorted` for usage details""" |
| 423 | # Get sort key, direction, and limit |
| 424 | if key not in ['expires', 'size', 'key']: |
| 425 | raise ValueError(f'Invalid sort key: {key}') |
| 426 | if key == 'size': |
| 427 | key = 'LENGTH(value)' |
| 428 | direction = 'DESC' if reversed else 'ASC' |
| 429 | limit_expr = f'LIMIT {limit}' if limit else '' |
| 430 | |
| 431 | # Filter out expired items, if specified |
| 432 | filter_expr = '' |
| 433 | params: Tuple = () |
| 434 | if not expired: |
| 435 | filter_expr = 'WHERE expires is null or expires > ?' |
| 436 | params = (time(),) |
| 437 | |
| 438 | with self.connection() as con: |
| 439 | for row in con.execute( |
| 440 | f'SELECT key, value FROM {self.table_name} {filter_expr}' |
| 441 | f' ORDER BY {key} {direction} {limit_expr}', |
| 442 | params, |
| 443 | ): |
| 444 | result = self.deserialize(row[0], row[1]) |
| 445 | # Omit any results that can't be deserialized |
| 446 | if result: |
| 447 | yield result |
| 448 | |
| 449 | def vacuum(self): |
| 450 | # VACUUM cannot run inside a transaction; acquire the lock and run it directly |