-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkey_value_api.py
67 lines (50 loc) · 1.96 KB
/
key_value_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""TcEx Framework Module"""
# standard library
from typing import Any
from urllib.parse import quote
# third-party
from requests import Session
from .key_value_abc import KeyValueABC
class KeyValueApi(KeyValueABC):
"""TcEx Key Value API Module.
Args:
session: A configured requests session for TC API (tcex.session).
"""
def __init__(self, session: Session):
"""Initialize the Class properties."""
self._session = session
# properties
self.kv_type = 'api'
def create(self, context: str, key: str, value: Any) -> int:
"""Create key/value pair in remote KV store.
Args:
context: A specific context for the create.
key: The key to create in remote KV store.
value: The value to store in remote KV store.
Returns:
(string): The response from the API call.
"""
key = quote(key, safe='~')
headers = {'content-type': 'application/octet-stream'}
url = f'/internal/playbooks/keyValue/{context}/{key}'
r = self._session.put(url, data=value, headers=headers)
if r.ok:
# the redis client returns the count of items added, in this case there is only one
return 1
return 0 # no entries created
def read(self, context: str, key: str) -> bytes | str | None:
"""Read data from remote KV store for the provided key.
Args:
context: A specific context for the create.
key: The key to read in remote KV store.
Returns:
(any): The response data from the remote KV store.
"""
key = quote(key, safe='~')
url = f'/internal/playbooks/keyValue/{context}/{key}'
r = self._session.get(url)
data = r.content
# Binary data for PB Apps is base64 encoded, for service Apps it is not
if data is not None and isinstance(data, bytes):
data = data.decode('utf-8')
return data