wuenlp_tools.keys.lazykeys

 1import json
 2import os
 3from collections import UserString
 4
 5KEYS_PATH = os.path.expanduser("~/.local/share/wuenlp-tools/keys.json")
 6
 7
 8def read_keys():
 9    """Read keys from the JSON file. Returns an empty dict if the file doesn't exist or is corrupted."""
10    if os.path.isfile(KEYS_PATH):
11        try:
12            with open(KEYS_PATH, "r") as f:
13                return json.load(f)
14        except json.JSONDecodeError:
15            return {}
16    return {}
17
18
19def write_keys(keys):
20    """Write the keys dictionary to the JSON file."""
21    os.makedirs(os.path.dirname(KEYS_PATH), exist_ok=True)
22    with open(KEYS_PATH, "w") as f:
23        json.dump(keys, f, indent=2)
24
25
26def get_api_key(key_name):
27    """
28    Get an API key by name from the file.
29    If not present, prompt the user and store it.
30    """
31    keys = read_keys()
32    if key_name in keys:
33        return keys[key_name]
34    else:
35        key_value = input(f"Please enter the API key for {key_name}: ").strip()
36        keys[key_name] = key_value
37        write_keys(keys)
38        return key_value
39
40
41class LazyKey(UserString):
42    """
43    A lazy-loading key that behaves like a string using UserString.
44
45    The actual API key is only requested (and cached) when the underlying data is accessed.
46    """
47
48    def __init__(self, key_name):
49        self.key_name = key_name
50        self._loaded = False
51        self._data = None  # _data will hold the actual key value
52        # We intentionally initialize the UserString with an empty string.
53        super().__init__("")
54
55    @property
56    def data(self):
57        """Load and cache the data on first access."""
58        if not self._loaded:
59            self._data = get_api_key(self.key_name)
60            self._loaded = True
61        return self._data
62
63    @data.setter
64    def data(self, value):
65        self._data = value
66
67    def __str__(self):
68        return self.data
69
70    def __repr__(self):
71        return repr(self.data)
72
73    # UserString uses self.data for many of its operations, so we simply return the loaded data.
74    def __add__(self, other):
75        return self.data + other
76
77    def __radd__(self, other):
78        return other + self.data
KEYS_PATH = '/Users/zehe/.local/share/wuenlp-tools/keys.json'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

def read_keys():
 9def read_keys():
10    """Read keys from the JSON file. Returns an empty dict if the file doesn't exist or is corrupted."""
11    if os.path.isfile(KEYS_PATH):
12        try:
13            with open(KEYS_PATH, "r") as f:
14                return json.load(f)
15        except json.JSONDecodeError:
16            return {}
17    return {}

Read keys from the JSON file. Returns an empty dict if the file doesn't exist or is corrupted.

def write_keys(keys):
20def write_keys(keys):
21    """Write the keys dictionary to the JSON file."""
22    os.makedirs(os.path.dirname(KEYS_PATH), exist_ok=True)
23    with open(KEYS_PATH, "w") as f:
24        json.dump(keys, f, indent=2)

Write the keys dictionary to the JSON file.

def get_api_key(key_name):
27def get_api_key(key_name):
28    """
29    Get an API key by name from the file.
30    If not present, prompt the user and store it.
31    """
32    keys = read_keys()
33    if key_name in keys:
34        return keys[key_name]
35    else:
36        key_value = input(f"Please enter the API key for {key_name}: ").strip()
37        keys[key_name] = key_value
38        write_keys(keys)
39        return key_value

Get an API key by name from the file. If not present, prompt the user and store it.

class LazyKey(collections.UserString):
42class LazyKey(UserString):
43    """
44    A lazy-loading key that behaves like a string using UserString.
45
46    The actual API key is only requested (and cached) when the underlying data is accessed.
47    """
48
49    def __init__(self, key_name):
50        self.key_name = key_name
51        self._loaded = False
52        self._data = None  # _data will hold the actual key value
53        # We intentionally initialize the UserString with an empty string.
54        super().__init__("")
55
56    @property
57    def data(self):
58        """Load and cache the data on first access."""
59        if not self._loaded:
60            self._data = get_api_key(self.key_name)
61            self._loaded = True
62        return self._data
63
64    @data.setter
65    def data(self, value):
66        self._data = value
67
68    def __str__(self):
69        return self.data
70
71    def __repr__(self):
72        return repr(self.data)
73
74    # UserString uses self.data for many of its operations, so we simply return the loaded data.
75    def __add__(self, other):
76        return self.data + other
77
78    def __radd__(self, other):
79        return other + self.data

A lazy-loading key that behaves like a string using UserString.

The actual API key is only requested (and cached) when the underlying data is accessed.

LazyKey(key_name)
49    def __init__(self, key_name):
50        self.key_name = key_name
51        self._loaded = False
52        self._data = None  # _data will hold the actual key value
53        # We intentionally initialize the UserString with an empty string.
54        super().__init__("")
key_name
data
56    @property
57    def data(self):
58        """Load and cache the data on first access."""
59        if not self._loaded:
60            self._data = get_api_key(self.key_name)
61            self._loaded = True
62        return self._data

Load and cache the data on first access.