Skip to content

Caching

BaseCache

BaseCache persistence interface.

Purpose

Defines the cache interface for dictionaries, expiration, and namespace keys.

Attributes:

Name Type Description
None

The abstract interface has no declared instance attributes.

Methods:

get

get(key: str) -> Optional[Dict[str, Any]]

Retrieve an entry by its cache key.

Purpose

Retrieve an entry by its cache key.

Parameters:

Name Type Description Default
key str

Cache key identifying the record.

required

Returns:

Type Description
Optional[Dict[str, Any]]

Optional[ Dict[ str, Any ] ]: Result of the get operation.

Source code in storage.py
def get( self, key: str ) -> Optional[ Dict[ str, Any ] ]:
	"""Retrieve an entry by its cache key.

	Purpose:
		Retrieve an entry by its cache key.

	Args:
		key (str): Cache key identifying the record.

	Returns:
		Optional[ Dict[ str, Any ] ]: Result of the get operation.
	"""
	raise NotImplementedError

set

set(
    key: str,
    value: Dict[str, Any],
    ttl: Optional[int] = None,
) -> None

Store a key/value pair with an optional time-to-live.

Purpose

Store a key/value pair with an optional time-to-live.

Parameters:

Name Type Description Default
key str

Cache key identifying the record.

required
value Dict[str, Any]

Value or user-entered filter value.

required
ttl Optional[int]

Optional time-to-live in seconds.

None

Returns:

Name Type Description
None None

Completes the operation through side effects.

Source code in storage.py
def set( self, key: str, value: Dict[ str, Any ], ttl: Optional[ int ] = None ) -> None:
	"""Store a key/value pair with an optional time-to-live.

	Purpose:
		Store a key/value pair with an optional time-to-live.

	Args:
		key (str): Cache key identifying the record.
		value (Dict[ str, Any ]): Value or user-entered filter value.
		ttl (Optional[ int ]): Optional time-to-live in seconds.

	Returns:
		None: Completes the operation through side effects.
	"""
	raise NotImplementedError

delete

delete(key: str) -> None

Remove a cache entry.

Purpose

Remove a cache entry.

Parameters:

Name Type Description Default
key str

Cache key identifying the record.

required

Returns:

Name Type Description
None None

Completes the operation through side effects.

Source code in storage.py
def delete( self, key: str ) -> None:
	"""Remove a cache entry.

	Purpose:
		Remove a cache entry.

	Args:
		key (str): Cache key identifying the record.

	Returns:
		None: Completes the operation through side effects.
	"""
	raise NotImplementedError

clear

clear(namespace: Optional[str] = None) -> None

Clear entries matching an optional namespace.

Purpose

Clear entries matching an optional namespace.

Parameters:

Name Type Description Default
namespace Optional[str]

Optional cache namespace.

None

Returns:

Name Type Description
None None

Completes the operation through side effects.

Source code in storage.py
def clear( self, namespace: Optional[ str ] = None ) -> None:
	"""Clear entries matching an optional namespace.

	Purpose:
		Clear entries matching an optional namespace.

	Args:
		namespace (Optional[ str ]): Optional cache namespace.

	Returns:
		None: Completes the operation through side effects.
	"""
	raise NotImplementedError

contains

contains(key: str) -> bool

Determine whether a cache entry exists.

Purpose

Determine whether a cache entry exists.

Parameters:

Name Type Description Default
key str

Cache key identifying the record.

required

Returns:

Name Type Description
bool bool

Result of the contains operation.

Source code in storage.py
def contains( self, key: str ) -> bool:
	"""Determine whether a cache entry exists.

	Purpose:
		Determine whether a cache entry exists.

	Args:
		key (str): Cache key identifying the record.

	Returns:
		bool: Result of the contains operation.
	"""
	try:
		throw_if( 'key', key )
		return self.get( key ) is not None
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'BaseCache'
		exception.method = "contains( self, key: str ) -> bool"
		Logger( ).write( exception )
		raise exception

namespace_key

namespace_key(namespace: str, key: str) -> str
    Create a cache key prefixed by a namespace.
Purpose

Create a cache key prefixed by a namespace.

Parameters:

Name Type Description Default
namespace str

Logical cache namespace, such as geocode, places, weather, distance, or fetcher.

required
key str

Raw cache key.

required

Returns:

Name Type Description
str str

Namespace-qualified cache key.

Source code in storage.py
def namespace_key( self, namespace: str, key: str ) -> str:
	"""
		Create a cache key prefixed by a namespace.

	Purpose:
		Create a cache key prefixed by a namespace.

	Args:
		namespace (str): Logical cache namespace, such as geocode, places, weather,
			distance, or fetcher.

		key (str): Raw cache key.

	Returns:
		str: Namespace-qualified cache key.
	"""
	try:
		throw_if( 'namespace', namespace )
		throw_if( 'key', key )
		return f'{namespace}::{key}'
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'BaseCache'
		exception.method = "namespace_key( self, namespace: str, key: str ) -> str"
		Logger( ).write( exception )
		raise exception

stats

stats() -> Dict[str, Any]

Return cache usage and diagnostic statistics.

Purpose

Return cache usage and diagnostic statistics.

Returns:

Type Description
Dict[str, Any]

Dict[ str, Any ]: Result of the stats operation.

Source code in storage.py
def stats( self ) -> Dict[ str, Any ]:
	"""Return cache usage and diagnostic statistics.

	Purpose:
		Return cache usage and diagnostic statistics.

	Returns:
		Dict[ str, Any ]: Result of the stats operation.
	"""
	raise NotImplementedError

InMemoryCache

InMemoryCache()

Bases: BaseCache

InMemoryCache persistence interface.

Purpose

Caches records in memory and tracks cache use, writes, and deletions.

Attributes:

Name Type Description
store Dict[str, Dict[str, Any]]

Internal cache record dictionary.

hits int

Successful cache reads.

misses int

Unsuccessful cache reads.

sets int

Cache writes.

deletes int

Deleted cache entries.

Initialize empty cache records and operation counters.

Purpose

Initialize empty cache records and operation counters.

Returns:

Name Type Description
None None

Completes the operation through side effects.

Source code in storage.py
def __init__( self ) -> None:
	"""Initialize empty cache records and operation counters.

	Purpose:
		Initialize empty cache records and operation counters.

	Returns:
		None: Completes the operation through side effects.
	"""
	self.store = { }
	self.hits = 0
	self.misses = 0
	self.sets = 0
	self.deletes = 0

Methods:

now

now() -> float
    Return the current Unix timestamp.
Purpose

Return the current Unix timestamp.

Returns:

Name Type Description
float float

Current Unix timestamp.

Source code in storage.py
def now( self ) -> float:
	"""
		Return the current Unix timestamp.

	Purpose:
		Return the current Unix timestamp.

	Returns:
		float: Current Unix timestamp.
	"""
	try:
		return time.time( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'InMemoryCache'
		exception.method = "now( self ) -> float"
		Logger( ).write( exception )
		raise exception

make_record

make_record(
    key: str,
    value: Dict[str, Any],
    ttl: Optional[int] = None,
) -> Dict[str, Any]
    Create a cache metadata record for the supplied key and value.
Purpose

Create a cache metadata record for the supplied key and value.

Parameters:

Name Type Description Default
key str

Cache key.

required
value Dict[str, Any]

JSON-serializable cache value.

required
ttl Optional[int]

Optional time-to-live in seconds.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Cache metadata record.

Source code in storage.py
def make_record( self, key: str, value: Dict[ str, Any ], ttl: Optional[ int ] = None ) -> Dict[
	str, Any ]:
	"""
		Create a cache metadata record for the supplied key and value.

	Purpose:
		Create a cache metadata record for the supplied key and value.

	Args:
		key (str): Cache key.

		value (Dict[str, Any]): JSON-serializable cache value.

		ttl (Optional[int]): Optional time-to-live in seconds.

	Returns:
		Dict[str, Any]: Cache metadata record.
	"""
	try:
		throw_if( 'key', key )
		throw_if( 'value', value )
		now_value = self.now( )
		ttl_value = int( ttl ) if ttl is not None and int( ttl ) > 0 else None
		expires_value = now_value + ttl_value if ttl_value else None
		return { 'key': key, 'value': value, 'created_at': now_value, 'updated_at': now_value,
			'expires_at': expires_value, 'hit_count': 0, 'last_accessed': None }

	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'InMemoryCache'
		exception.method = (
			"make_record( self, key: str, value: Dict[ str, Any ], ttl: Optional[ int ] = None ) "
			"-> Dict[ str, Any ]:")
		Logger( ).write( exception )
		raise exception

is_expired

is_expired(record: Dict[str, Any]) -> bool
    Determine whether an in-memory cache record has expired.
Purpose

Determine whether an in-memory cache record has expired.

Parameters:

Name Type Description Default
record Dict[str, Any]

Cache metadata record.

required

Returns:

Name Type Description
bool bool

True if expired; otherwise False.

Source code in storage.py
def is_expired( self, record: Dict[ str, Any ] ) -> bool:
	"""
		Determine whether an in-memory cache record has expired.

	Purpose:
		Determine whether an in-memory cache record has expired.

	Args:
		record (Dict[str, Any]): Cache metadata record.

	Returns:
		bool: True if expired; otherwise False.
	"""
	try:
		throw_if( 'record', record )
		expires_at = record.get( 'expires_at' )
		if expires_at is None:
			return False
		return float( expires_at ) <= self.now( )

	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'InMemoryCache'
		exception.method = "is_expired( self, record: Dict[ str, Any ] ) -> bool"
		Logger( ).write( exception )
		raise exception

get

get(key: str) -> Optional[Dict[str, Any]]
    Return a cached value by key when present and not expired.
Purpose

Return a cached value by key when present and not expired.

Parameters:

Name Type Description Default
key str

Cache key.

required

Returns:

Type Description
Optional[Dict[str, Any]]

Optional[Dict[str, Any]]: Cached value or None.

Source code in storage.py
def get( self, key: str ) -> Optional[ Dict[ str, Any ] ]:
	"""
		Return a cached value by key when present and not expired.

	Purpose:
		Return a cached value by key when present and not expired.

	Args:
		key (str): Cache key.

	Returns:
		Optional[Dict[str, Any]]: Cached value or None.
	"""
	try:
		throw_if( 'key', key )
		record = self.store.get( key )
		if not record:
			self.misses += 1
			return None
		if self.is_expired( record ):
			self.delete( key )
			self.misses += 1
			return None
		record[ 'hit_count' ] = int( record.get( 'hit_count', 0 ) or 0 ) + 1
		record[ 'last_accessed' ] = self.now( )
		self.hits += 1
		return record.get( 'value' )
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'InMemoryCache'
		exception.method = "get( self, key: str ) -> Optional[ Dict[ str, Any ] ]"
		Logger( ).write( exception )
		raise exception

set

set(
    key: str,
    value: Dict[str, Any],
    ttl: Optional[int] = None,
) -> None
    Set a cache value by key.
Purpose

Set a cache value by key.

Parameters:

Name Type Description Default
key str

Cache key.

required
value Dict[str, Any]

JSON-serializable cache value.

required
ttl Optional[int]

Optional time-to-live in seconds.

None

Returns:

Type Description
None

None.

Source code in storage.py
def set( self, key: str, value: Dict[ str, Any ], ttl: Optional[ int ] = None ) -> None:
	"""
		Set a cache value by key.

	Purpose:
		Set a cache value by key.

	Args:
		key (str): Cache key.

		value (Dict[str, Any]): JSON-serializable cache value.

		ttl (Optional[int]): Optional time-to-live in seconds.

	Returns:
		None.
	"""
	try:
		throw_if( 'key', key )
		throw_if( 'value', value )
		self.store[ key ] = self.make_record( key, value, ttl )
		self.sets += 1
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'InMemoryCache'
		exception.method = "set( self, key: str, value: Dict[ str, Any ], ttl: Optional[ int ] = None ) -> None"
		Logger( ).write( exception )
		raise exception

delete

delete(key: str) -> None
    Delete a cache entry by key.
Purpose

Delete a cache entry by key.

Parameters:

Name Type Description Default
key str

Cache key.

required

Returns:

Type Description
None

None.

Source code in storage.py
def delete( self, key: str ) -> None:
	"""
		Delete a cache entry by key.

	Purpose:
		Delete a cache entry by key.

	Args:
		key (str): Cache key.

	Returns:
		None.
	"""
	try:
		throw_if( 'key', key )
		if key in self.store:
			del self.store[ key ]
			self.deletes += 1
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'InMemoryCache'
		exception.method = "delete( self, key: str ) -> None"
		Logger( ).write( exception )
		raise exception

clear

clear(namespace: Optional[str] = None) -> None
    Clear all cache entries or only entries under a namespace prefix.
Purpose

Clear all cache entries or only entries under a namespace prefix.

Parameters:

Name Type Description Default
namespace Optional[str]

Optional namespace prefix.

None

Returns:

Type Description
None

None.

Source code in storage.py
def clear( self, namespace: Optional[ str ] = None ) -> None:
	"""
		Clear all cache entries or only entries under a namespace prefix.

	Purpose:
		Clear all cache entries or only entries under a namespace prefix.

	Args:
		namespace (Optional[str]): Optional namespace prefix.

	Returns:
		None.
	"""
	try:
		if namespace:
			prefix = f'{namespace}::'
			keys = [ key for key in self.store if key.startswith( prefix ) ]
			for key in keys:
				self.delete( key )
		else:
			deleted = len( self.store )
			self.store.clear( )
			self.deletes += deleted
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'InMemoryCache'
		exception.method = "clear( self, namespace: Optional[ str ] = None ) -> None"
		Logger( ).write( exception )
		raise exception

contains

contains(key: str) -> bool
    Determine whether a cache key exists and is not expired.
Purpose

Determine whether a cache key exists and is not expired.

Parameters:

Name Type Description Default
key str

Cache key.

required

Returns:

Name Type Description
bool bool

True if the key exists and is not expired.

Source code in storage.py
def contains( self, key: str ) -> bool:
	"""
		Determine whether a cache key exists and is not expired.

	Purpose:
		Determine whether a cache key exists and is not expired.

	Args:
		key (str): Cache key.

	Returns:
		bool: True if the key exists and is not expired.
	"""
	try:
		throw_if( 'key', key )
		return self.get( key ) is not None
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'InMemoryCache'
		exception.method = "contains( self, key: str ) -> bool"
		Logger( ).write( exception )
		raise exception

stats

stats() -> Dict[str, Any]
    Return cache diagnostics.
Purpose

Return cache diagnostics.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Cache diagnostics.

Source code in storage.py
def stats( self ) -> Dict[ str, Any ]:
	"""
		Return cache diagnostics.

	Purpose:
		Return cache diagnostics.

	Returns:
		Dict[str, Any]: Cache diagnostics.
	"""
	try:
		expired = 0
		for record in self.store.values( ):
			if self.is_expired( record ):
				expired += 1
		return { 'backend': 'memory', 'entries': len( self.store ), 'expired_entries': expired,
			'hits': self.hits, 'misses': self.misses, 'sets': self.sets,
			'deletes': self.deletes }
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'InMemoryCache'
		exception.method = "stats( self ) -> Dict[ str, Any ]"
		Logger( ).write( exception )
		raise exception

namespace_key

namespace_key(namespace: str, key: str) -> str
    Create a cache key prefixed by a namespace.
Purpose

Create a cache key prefixed by a namespace.

Parameters:

Name Type Description Default
namespace str

Logical cache namespace, such as geocode, places, weather, distance, or fetcher.

required
key str

Raw cache key.

required

Returns:

Name Type Description
str str

Namespace-qualified cache key.

Source code in storage.py
def namespace_key( self, namespace: str, key: str ) -> str:
	"""
		Create a cache key prefixed by a namespace.

	Purpose:
		Create a cache key prefixed by a namespace.

	Args:
		namespace (str): Logical cache namespace, such as geocode, places, weather,
			distance, or fetcher.

		key (str): Raw cache key.

	Returns:
		str: Namespace-qualified cache key.
	"""
	try:
		throw_if( 'namespace', namespace )
		throw_if( 'key', key )
		return f'{namespace}::{key}'
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'BaseCache'
		exception.method = "namespace_key( self, namespace: str, key: str ) -> str"
		Logger( ).write( exception )
		raise exception

SQLiteCache

SQLiteCache(path: str = 'mappy_cache.sqlite')

Bases: BaseCache

SQLiteCache persistence interface.

Purpose

Persists cache records and time-to-live metadata in an on-disk SQLite database.

Attributes:

Name Type Description
path Optional[str]

SQLite cache file path.

connection Connection

Active SQLite cache connection.

Open the SQLite cache file and initialize its schema.

Purpose

Open the SQLite cache file and initialize its schema.

Parameters:

Name Type Description Default
path str

SQLite database filename.

'mappy_cache.sqlite'

Returns:

Name Type Description
None None

Completes the operation through side effects.

Source code in storage.py
def __init__( self, path: str = 'mappy_cache.sqlite' ) -> None:
	"""Open the SQLite cache file and initialize its schema.

	Purpose:
		Open the SQLite cache file and initialize its schema.

	Args:
		path (str): SQLite database filename.

	Returns:
		None: Completes the operation through side effects.
	"""
	self.path = path
	d = os.path.dirname( self.path )
	if d:
		os.makedirs( d, exist_ok=True )
	self.connection = sqlite3.connect( self.path )
	self.initialize( )

Methods:

initialize

initialize() -> None
    Create the SQLite cache table when it does not already exist.
Purpose

Create the SQLite cache table when it does not already exist.

Returns:

Type Description
None

None.

Source code in storage.py
	def initialize( self ) -> None:
		"""
			Create the SQLite cache table when it does not already exist.

		Purpose:
			Create the SQLite cache table when it does not already exist.

		Returns:
			None.
		"""
		try:
			self.connection.execute( '''
                                     CREATE TABLE IF NOT EXISTS kv
                                     (
                                         k
                                         TEXT
                                         PRIMARY
                                         KEY,
                                         v
                                         TEXT
                                         NOT
                                         NULL,
                                         created_at
                                         REAL,
                                         updated_at
                                         REAL,
                                         expires_at
                                         REAL,
                                         hit_count
                                         INTEGER
                                         DEFAULT
                                         0,
                                         last_accessed
                                         REAL
                                     ) ''' )
			self.migrate( )
			self.connection.commit( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'storage'
			exception.cause = 'SQLiteCache'
			exception.method = "initialize( self ) -> None"
			Logger( ).write( exception )
			raise exception

migrate

migrate() -> None
    Add metadata columns to older kv tables that only contain k and v.
Purpose

Add metadata columns to older kv tables that only contain k and v.

Returns:

Type Description
None

None.

Source code in storage.py
def migrate( self ) -> None:
	"""
		Add metadata columns to older kv tables that only contain k and v.

	Purpose:
		Add metadata columns to older kv tables that only contain k and v.

	Returns:
		None.
	"""
	try:
		cursor = self.connection.execute( 'PRAGMA table_info(kv)' )
		columns = { row[ 1 ] for row in cursor.fetchall( ) }
		additions = { 'created_at': 'ALTER TABLE kv ADD COLUMN created_at REAL',
			'updated_at': 'ALTER TABLE kv ADD COLUMN updated_at REAL',
			'expires_at': 'ALTER TABLE kv ADD COLUMN expires_at REAL',
			'hit_count': 'ALTER TABLE kv ADD COLUMN hit_count INTEGER DEFAULT 0',
			'last_accessed': 'ALTER TABLE kv ADD COLUMN last_accessed REAL' }
		for column, sql in additions.items( ):
			if column not in columns:
				self.connection.execute( sql )

	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'SQLiteCache'
		exception.method = "migrate( self ) -> None"
		Logger( ).write( exception )
		raise exception

now

now() -> float
    Return the current Unix timestamp.
Purpose

Return the current Unix timestamp.

Returns:

Name Type Description
float float

Current Unix timestamp.

Source code in storage.py
def now( self ) -> float:
	"""
		Return the current Unix timestamp.

	Purpose:
		Return the current Unix timestamp.

	Returns:
		float: Current Unix timestamp.
	"""
	try:
		return time.time( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'SQLiteCache'
		exception.method = "now( self ) -> float"
		Logger( ).write( exception )
		raise exception

get

get(key: str) -> Optional[Dict[str, Any]]
    Return a cached value by key when present and not expired.
Purpose

Return a cached value by key when present and not expired.

Parameters:

Name Type Description Default
key str

Cached value or None.

required

Returns:

Type Description
Optional[Dict[str, Any]]

Optional[ Dict[ str, Any ] ]: Result of the get operation.

Source code in storage.py
def get( self, key: str ) -> Optional[ Dict[ str, Any ] ]:
	"""
		Return a cached value by key when present and not expired.

	Purpose:
		Return a cached value by key when present and not expired.

	Args:
		key (str): Cached value or None.

	Returns:
		Optional[ Dict[ str, Any ] ]: Result of the get operation.
	"""
	try:
		throw_if( 'key', key )
		statement = 'SELECT v, expires_at, hit_count FROM kv WHERE k = ?'
		cursor = self.connection.execute( statement, (key,) )
		row = cursor.fetchone( )
		if not row:
			return None
		payload = row[ 0 ]
		expires_at = row[ 1 ]
		hit_count = int( row[ 2 ] or 0 )
		if expires_at is not None and float( expires_at ) <= self.now( ):
			self.delete( key )
			return None
		self.connection.execute( 'UPDATE kv SET hit_count = ?, last_accessed = ? WHERE k = ?', (
			hit_count + 1, self.now( ), key) )
		self.connection.commit( )
		return json.loads( payload )
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'SQLiteCache'
		exception.method = "get( self, key: str ) -> Optional[ Dict[ str, Any ] ]"
		Logger( ).write( exception )
		raise exception

set

set(
    key: str,
    value: Dict[str, Any],
    ttl: Optional[int] = None,
) -> None
    Set a cache value by key.
Purpose

Set a cache value by key.

Parameters:

Name Type Description Default
key str

Cache key.

required
value Dict[str, Any]

JSON-serializable cache value.

required
ttl Optional[int]

Optional time-to-live in seconds.

None

Returns:

Type Description
None

None.

Source code in storage.py
	def set( self, key: str, value: Dict[ str, Any ], ttl: Optional[ int ] = None ) -> None:
		"""
			Set a cache value by key.

		Purpose:
			Set a cache value by key.

		Args:
			key (str): Cache key.
			value (Dict[str, Any]): JSON-serializable cache value.
			ttl (Optional[int]): Optional time-to-live in seconds.

		Returns:
			None.
		"""
		try:
			throw_if( 'key', key )
			throw_if( 'value', value )
			now_value = self.now( )
			ttl_value = int( ttl ) if ttl is not None and int( ttl ) > 0 else None
			expires_value = now_value + ttl_value if ttl_value else None
			payload = json.dumps( value, ensure_ascii=False )
			self.connection.execute( ''' INSERT INTO kv
                                         (k, v, created_at, updated_at, expires_at, hit_count,
                                          last_accessed)
                                         VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(k) DO
            UPDATE SET
                v = excluded.v,
                updated_at = excluded.updated_at,
                expires_at = excluded.expires_at
			                         ''', (key, payload, now_value, now_value, expires_value, 0,
				None) )
			self.connection.commit( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'storage'
			exception.cause = 'SQLiteCache'
			exception.method = "set( self, key: str, value: Dict[ str, Any ], ttl: Optional[ int ]=None ) -> None"
			Logger( ).write( exception )
			raise exception

delete

delete(key: str) -> None
    Delete a cache entry by key.
Purpose

Delete a cache entry by key.

Parameters:

Name Type Description Default
key str

Cache key.

required

Returns:

Type Description
None

None.

Source code in storage.py
def delete( self, key: str ) -> None:
	"""
		Delete a cache entry by key.

	Purpose:
		Delete a cache entry by key.

	Args:
		key (str): Cache key.

	Returns:
		None.
	"""
	try:
		throw_if( 'key', key )
		self.connection.execute( 'DELETE FROM kv WHERE k = ?', (key,) )
		self.connection.commit( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'SQLiteCache'
		exception.method = "delete( self, key: str ) -> None"
		Logger( ).write( exception )
		raise exception

clear

clear(namespace: Optional[str] = None) -> None
    Clear all cache entries or only entries under a namespace prefix.
Purpose

Clear all cache entries or only entries under a namespace prefix.

Parameters:

Name Type Description Default
namespace Optional[str]

Optional namespace prefix.

None

Returns:

Type Description
None

None.

Source code in storage.py
def clear( self, namespace: Optional[ str ] = None ) -> None:
	"""
		Clear all cache entries or only entries under a namespace prefix.

	Purpose:
		Clear all cache entries or only entries under a namespace prefix.

	Args:
		namespace (Optional[str]): Optional namespace prefix.

	Returns:
		None.
	"""
	try:
		if namespace:
			prefix = f'{namespace}::%'
			self.connection.execute( 'DELETE FROM kv WHERE k LIKE ?', (prefix,) )
		else:
			self.connection.execute( 'DELETE FROM kv' )
		self.connection.commit( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'SQLiteCache'
		exception.method = "clear( self, namespace: Optional[ str ]=None ) -> None"
		Logger( ).write( exception )
		raise exception

contains

contains(key: str) -> bool
    Determine whether a cache key exists and is not expired.
Purpose

Determine whether a cache key exists and is not expired.

Parameters:

Name Type Description Default
key str

Cache key.

required

Returns:

Name Type Description
bool bool

True if the key exists and is not expired.

Source code in storage.py
def contains( self, key: str ) -> bool:
	"""
		Determine whether a cache key exists and is not expired.

	Purpose:
		Determine whether a cache key exists and is not expired.

	Args:
		key (str): Cache key.

	Returns:
		bool: True if the key exists and is not expired.
	"""
	try:
		throw_if( 'key', key )
		return self.get( key ) is not None
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'SQLiteCache'
		exception.method = "contains( self, key: str ) -> bool"
		Logger( ).write( exception )
		raise exception

purge_expired

purge_expired() -> int
    Delete expired cache entries.
Purpose

Delete expired cache entries.

Returns:

Name Type Description
int int

Number of rows deleted.

Source code in storage.py
def purge_expired( self ) -> int:
	"""
		Delete expired cache entries.

	Purpose:
		Delete expired cache entries.

	Returns:
		int: Number of rows deleted.
	"""
	try:
		cursor = self.connection.execute( 'SELECT COUNT(*) FROM kv WHERE expires_at IS NOT NULL AND expires_at <= ?', (
			self.now( ),) )
		count = int( cursor.fetchone( )[ 0 ] or 0 )
		self.connection.execute( 'DELETE FROM kv WHERE expires_at IS NOT NULL AND expires_at <= ?', (
			self.now( ),) )
		self.connection.commit( )
		return count
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'SQLiteCache'
		exception.method = "purge_expired( self ) -> int"
		Logger( ).write( exception )
		raise exception

stats

stats() -> Dict[str, Any]
    Return SQLite cache diagnostics.
Purpose

Return SQLite cache diagnostics.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Cache diagnostics.

Source code in storage.py
def stats( self ) -> Dict[ str, Any ]:
	"""
		Return SQLite cache diagnostics.

	Purpose:
		Return SQLite cache diagnostics.

	Returns:
		Dict[str, Any]: Cache diagnostics.
	"""
	try:
		total = self.connection.execute( 'SELECT COUNT(*) FROM kv' ).fetchone( )[ 0 ]
		expired = \
		self.connection.execute( 'SELECT COUNT(*) FROM kv WHERE expires_at IS NOT NULL AND expires_at <= ?', (
			self.now( ),) ).fetchone( )[ 0 ]
		hits = \
		self.connection.execute( 'SELECT COALESCE(SUM(hit_count), 0) FROM kv' ).fetchone( )[ 0 ]
		return { 'backend': 'sqlite', 'path': self.path, 'entries': int( total or 0 ),
			'expired_entries': int( expired or 0 ), 'hits': int( hits or 0 ) }
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'SQLiteCache'
		exception.method = "stats( self ) -> Dict[ str, Any ]"
		Logger( ).write( exception )
		raise exception

close

close() -> None
    Close the SQLite connection.
Purpose

Close the SQLite connection.

Returns:

Type Description
None

None.

Source code in storage.py
def close( self ) -> None:
	"""
		Close the SQLite connection.

	Purpose:
		Close the SQLite connection.

	Returns:
		None.
	"""
	try:
		self.connection.close( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'SQLiteCache'
		exception.method = "close( self ) -> None"
		Logger( ).write( exception )
		raise exception

namespace_key

namespace_key(namespace: str, key: str) -> str
    Create a cache key prefixed by a namespace.
Purpose

Create a cache key prefixed by a namespace.

Parameters:

Name Type Description Default
namespace str

Logical cache namespace, such as geocode, places, weather, distance, or fetcher.

required
key str

Raw cache key.

required

Returns:

Name Type Description
str str

Namespace-qualified cache key.

Source code in storage.py
def namespace_key( self, namespace: str, key: str ) -> str:
	"""
		Create a cache key prefixed by a namespace.

	Purpose:
		Create a cache key prefixed by a namespace.

	Args:
		namespace (str): Logical cache namespace, such as geocode, places, weather,
			distance, or fetcher.

		key (str): Raw cache key.

	Returns:
		str: Namespace-qualified cache key.
	"""
	try:
		throw_if( 'namespace', namespace )
		throw_if( 'key', key )
		return f'{namespace}::{key}'
	except Exception as e:
		exception = Error( e )
		exception.module = 'storage'
		exception.cause = 'BaseCache'
		exception.method = "namespace_key( self, namespace: str, key: str ) -> str"
		Logger( ).write( exception )
		raise exception