Skip to content

Commit

Permalink
cache 'webservice'
Browse files Browse the repository at this point in the history
  • Loading branch information
xlcnd committed Apr 3, 2021
1 parent 854e11a commit 909021d
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
3 changes: 2 additions & 1 deletion isbnlib/dev/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"""Interface for namespace 'isbnlib.dev'."""

from ._data import Metadata, stdmeta
from ._decorators import cache
from ._decorators import cache, imcache
from ._exceptions import (
DataNotFoundAtServiceError,
DataWrongShapeError,
Expand Down Expand Up @@ -34,4 +34,5 @@
'WEBService',
'WEBQuery',
'cache',
'imcache',
)
29 changes: 28 additions & 1 deletion isbnlib/dev/_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@
# isort:skip_file
"""Decorator for isbnlib."""
from functools import wraps
from .._imcache import IMCache

im_cache = IMCache(maxlen=200)


def cache(func):
"""Cache decorator."""
"""Cache decorator (cache)."""
# noqa
@wraps(func)
def memoized_func(*args, **kwargs):
Expand All @@ -27,3 +30,27 @@ def memoized_func(*args, **kwargs):
return value

return memoized_func


def imcache(func):
"""Cache decorator (imcache)."""
# noqa
@wraps(func)
def memoized_func(*args, **kwargs):
cch = im_cache
if cch is None: # pragma: no cover
return func(*args, **kwargs)

# Persistent caches will NOT work IF
# 'func' has callables in the arguments
key = str(func.__name__) + str(args) + str(kwargs)

if key in cch:
return cch[key]
else:
value = func(*args, **kwargs)
if value:
cch[key] = value
return value

return memoized_func
2 changes: 2 additions & 0 deletions isbnlib/dev/webservice.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from socket import timeout as sockettimeout

from ..config import options
from . import imcache
from ._bouth23 import bstream, s
from ._exceptions import ISBNLibHTTPError, ISBNLibURLError, ServiceIsDownError

Expand Down Expand Up @@ -100,6 +101,7 @@ def data(self):
return s(data)


@imcache
def query(url, user_agent=UA, values=None, appheaders=None):
"""Query to a web service."""
service = WEBService(
Expand Down

0 comments on commit 909021d

Please sign in to comment.