rho-store 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.1
2
+ Name: rho-store
3
+ Version: 0.1.0
4
+ Summary:
5
+ Author: Björn Ström
6
+ Author-email: bjornstrom90@gmail.com
7
+ Requires-Python: >=3.10,<3.13
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Requires-Dist: dask (>=2023.10.1,<2024.0.0)
12
+ Requires-Dist: pandas (>=2.1.2,<3.0.0)
13
+ Requires-Dist: pyarrow (>=13.0.0,<14.0.0)
14
+ Requires-Dist: pytest (>=7.4.3,<8.0.0)
15
+ Requires-Dist: requests (>=2.31.0,<3.0.0)
16
+ Requires-Dist: responses (>=0.23.3,<0.24.0)
17
+ Requires-Dist: ujson (>=5.8.0,<6.0.0)
18
+ Description-Content-Type: text/markdown
19
+
20
+ # rho-store
21
+ Python SDK
22
+
23
+
@@ -0,0 +1,3 @@
1
+ # rho-store
2
+ Python SDK
3
+
@@ -0,0 +1,22 @@
1
+ [tool.poetry]
2
+ name = "rho-store"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = ["Björn Ström <bjornstrom90@gmail.com>"]
6
+ readme = "README.md"
7
+ packages = [{include = "rho_store"}]
8
+
9
+ [tool.poetry.dependencies]
10
+ python = ">=3.10,<3.13"
11
+ pandas = "^2.1.2"
12
+ dask = "^2023.10.1"
13
+ requests = "^2.31.0"
14
+ pytest = "^7.4.3"
15
+ responses = "^0.23.3"
16
+ pyarrow = "^13.0.0"
17
+ ujson = "^5.8.0"
18
+
19
+
20
+ [build-system]
21
+ requires = ["poetry-core"]
22
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1 @@
1
+ from .client import RhoClient
@@ -0,0 +1,2 @@
1
+ from .rho_api import *
2
+ from .upload_file import *
@@ -0,0 +1 @@
1
+ from .graphql_adapter import *
@@ -0,0 +1,117 @@
1
+ import requests
2
+ from requests.exceptions import RequestException
3
+
4
+ from rho_store.adapters.rho_api.utils import table_data_to_list
5
+ from rho_store.exceptions import RhoApiError
6
+
7
+
8
+ class RhoApiGraphqlAdapter:
9
+ def __init__(self, base_url: str, api_key: str):
10
+ self.base_url = base_url
11
+ self.api_key = api_key
12
+
13
+ self.session = requests.Session()
14
+
15
+ def get_signed_url(self) -> tuple[str, str]:
16
+ query = """
17
+ mutation GetUploadUrl {
18
+ getUploadUrl {
19
+ url
20
+ fileName
21
+ ok
22
+ errorCode
23
+ }
24
+ }
25
+ """
26
+ data, errors = self._make_request(query)
27
+ if errors:
28
+ raise RhoApiError(errors)
29
+ mutation_result = data["getUploadUrl"]
30
+ self._verify_mutation_result(mutation_result)
31
+ url = mutation_result["url"]
32
+ file_name = mutation_result["fileName"]
33
+ return url, file_name
34
+
35
+ def process_file(self, file_id: str) -> dict:
36
+ query = """
37
+ mutation ProcessFile($fileId: String!) {
38
+ processFile(fileId: $fileId) {
39
+ table {
40
+ id
41
+ name
42
+ workspaceId
43
+ }
44
+ ok
45
+ errorCode
46
+ }
47
+ }
48
+ """
49
+ variables = {"fileId": file_id}
50
+ data, errors = self._make_request(query, variables)
51
+ if errors:
52
+ raise RhoApiError(errors)
53
+ mutation_result = data["processFile"]
54
+ self._verify_mutation_result(mutation_result)
55
+ table = mutation_result["table"]
56
+ return table
57
+
58
+ def get_data(self, table_id: str) -> list[dict]:
59
+ query = """
60
+ query GetTableData($table_id: String!) {
61
+ tableData(tableId: $table_id) {
62
+ id
63
+ time
64
+ rows
65
+ columns
66
+ }
67
+ }
68
+ """
69
+ variables = {"table_id": table_id}
70
+ data, errors = self._make_request(query, variables=variables)
71
+ if errors:
72
+ raise RhoApiError(errors)
73
+ fetched_data = data["tableData"]
74
+ return table_data_to_list(fetched_data)
75
+
76
+ @staticmethod
77
+ def _verify_mutation_result(mutation_result: dict):
78
+ if not mutation_result["ok"]:
79
+ error_code = mutation_result["errorCode"]
80
+ raise RhoApiError(error_code)
81
+
82
+ def _make_request(self, query: str, variables: dict = None) -> tuple[dict, dict]:
83
+ payload = {"query": query, "operationName": self.get_operation_name(query)}
84
+ if variables:
85
+ payload["variables"] = variables
86
+ headers = self.get_headers()
87
+ response = self.session.post(self.base_url, json=payload, headers=headers)
88
+
89
+ try:
90
+ response.raise_for_status()
91
+ except RequestException as e:
92
+ raise RhoApiError(
93
+ f"Bad response from server: {response.status_code}"
94
+ ) from e
95
+
96
+ response_data = response.json()
97
+ print(response_data)
98
+ data, errors = response_data.get("data"), response_data.get("errors")
99
+ return data, errors
100
+
101
+ def get_headers(self):
102
+ return {
103
+ "Authorization": f"Bearer: {self.api_key}",
104
+ "Content-Type": "application/json",
105
+ "X-Api-Key": self.api_key,
106
+ }
107
+
108
+ @staticmethod
109
+ def get_operation_name(query: str) -> str:
110
+ first_part = query.split("{")[0].strip()
111
+ operation_name = first_part.split(" ")[1]
112
+ if "(" in operation_name:
113
+ operation_name = operation_name.split("(")[0]
114
+ return operation_name.strip()
115
+
116
+
117
+ __all__ = ["RhoApiGraphqlAdapter"]
@@ -0,0 +1,142 @@
1
+ import json
2
+
3
+ import pytest
4
+ import responses
5
+
6
+ from rho_store.adapters import RhoApiGraphqlAdapter
7
+ from rho_store.exceptions import RhoApiError
8
+ from tests.utils import random_string
9
+
10
+
11
+ @responses.activate
12
+ def test_get_signed_link_returns_correct_url():
13
+ # given
14
+ base_url = "https://example.com/graphql"
15
+ api_key = random_string()
16
+ api_port = RhoApiGraphqlAdapter(
17
+ base_url=base_url,
18
+ api_key=api_key
19
+ )
20
+ signed_url = f"https://magic-link.com?key={random_string()}"
21
+ file_name = random_string()
22
+ mock_response = {
23
+ "data": {
24
+ "getUploadUrl": {
25
+ "url": signed_url,
26
+ "fileName": file_name,
27
+ "ok": True,
28
+ "errorCode": None
29
+ }
30
+ }
31
+ }
32
+ responses.post(
33
+ base_url,
34
+ json=mock_response,
35
+ status=200
36
+ )
37
+
38
+ # when
39
+ received_url, received_file_name = api_port.get_signed_url()
40
+
41
+ # then
42
+ assert received_url == signed_url
43
+ assert received_file_name == file_name
44
+
45
+
46
+ @responses.activate
47
+ def test_get_signed_link_makes_correct_request():
48
+ # given
49
+ base_url = "https://example.com/graphql"
50
+ api_key = random_string()
51
+ api_port = RhoApiGraphqlAdapter(
52
+ base_url=base_url,
53
+ api_key=api_key
54
+ )
55
+ signed_url = f"https://magic-link.com?key={random_string()}"
56
+ mock_response = {
57
+ "data": {
58
+ "getUploadUrl": {
59
+ "url": signed_url,
60
+ "fileName": "a_filename",
61
+ "ok": True,
62
+ "errorCode": None
63
+ }
64
+ }
65
+ }
66
+ responses.post(
67
+ base_url,
68
+ json=mock_response,
69
+ status=200
70
+ )
71
+
72
+ # when
73
+ api_port.get_signed_url()
74
+
75
+ # then
76
+ last_request = responses.calls[0].request
77
+ last_request_data = json.loads(last_request.body)
78
+ assert "getUploadUrl" in last_request_data["query"]
79
+ assert last_request_data["operationName"]
80
+ auth_header = last_request.headers["Authorization"]
81
+ assert api_key in auth_header
82
+
83
+
84
+ @responses.activate
85
+ def test_get_signed_link_raises_exception_if_server_error():
86
+ # given
87
+ base_url = "https://example.com/graphql"
88
+ api_key = random_string()
89
+ api_port = RhoApiGraphqlAdapter(
90
+ base_url=base_url,
91
+ api_key=api_key
92
+ )
93
+ signed_url = f"https://magic-link.com?key={random_string()}"
94
+ mock_response = {
95
+ "data": {
96
+ "getUploadUrl": {
97
+ "url": signed_url,
98
+ "fileName": "a_filename",
99
+ "ok": True,
100
+ "errorCode": None
101
+ }
102
+ }
103
+ }
104
+ responses.post(
105
+ base_url,
106
+ json=mock_response,
107
+ status=500
108
+ )
109
+
110
+ # when/then
111
+ with pytest.raises(RhoApiError):
112
+ api_port.get_signed_url()
113
+
114
+
115
+ @responses.activate
116
+ def test_get_signed_link_raises_exception_error_in_response_body():
117
+ # given
118
+ base_url = "https://example.com/graphql"
119
+ api_key = random_string()
120
+ api_port = RhoApiGraphqlAdapter(
121
+ base_url=base_url,
122
+ api_key=api_key
123
+ )
124
+ error_code = "BAD_REQUEST"
125
+ mock_response = {
126
+ "data": {
127
+ "getUploadUrl": {
128
+ "url": None,
129
+ "ok": False,
130
+ "errorCode": error_code
131
+ }
132
+ }
133
+ }
134
+ responses.post(
135
+ base_url,
136
+ json=mock_response,
137
+ status=200
138
+ )
139
+
140
+ # when/then
141
+ with pytest.raises(RhoApiError):
142
+ api_port.get_signed_url()
@@ -0,0 +1,15 @@
1
+ import ujson
2
+
3
+
4
+ def table_data_to_list(table_data: dict) -> list[dict]:
5
+ rows_raw = table_data["rows"]
6
+ columns_raw = table_data["columns"]
7
+ rows = ujson.loads(rows_raw)
8
+ columns = ujson.loads(columns_raw)
9
+ return to_list(columns, rows)
10
+
11
+
12
+ def to_list(columns: list, rows: list[list], skip_first_col: bool = True) -> list[dict]:
13
+ # first column is internal "_id"-column
14
+ first_index = 1 if skip_first_col else 0
15
+ return [dict(zip(columns[first_index:], row[first_index:])) for row in rows]
@@ -0,0 +1 @@
1
+ from .http_adapter import *
@@ -0,0 +1,34 @@
1
+ import os
2
+ import uuid
3
+
4
+ import pandas as pd
5
+ import requests
6
+
7
+ from rho_store.file_utils import get_relative_path
8
+
9
+
10
+ class UploadFileHttpAdapter:
11
+ def __init__(self):
12
+ self.session = requests.Session()
13
+
14
+ def upload_file(self, url: str, file_data: bytes):
15
+ headers = {
16
+ 'Content-Type': 'application/octet-stream',
17
+ }
18
+ response = self.session.put(url, headers=headers, data=file_data)
19
+ response.raise_for_status()
20
+
21
+ def upload_dataframe(self, url: str, data: pd.DataFrame):
22
+ # 1. Dump file locally
23
+ temp_file_path = f"temp/{str(uuid.uuid4())}.parquet"
24
+ local_file_path = get_relative_path(temp_file_path, __file__)
25
+ data.to_parquet(local_file_path, engine="pyarrow")
26
+ # 2. Read file and upload
27
+ with open(local_file_path, 'rb') as f:
28
+ file_data = f.read()
29
+ self.upload_file(url, file_data)
30
+ # 3. delete file
31
+ os.remove(local_file_path)
32
+
33
+
34
+ __all__ = ["UploadFileHttpAdapter"]
@@ -0,0 +1,54 @@
1
+ import time
2
+
3
+ import pandas as pd
4
+
5
+ from .adapters import RhoApiGraphqlAdapter, UploadFileHttpAdapter
6
+
7
+
8
+ class RhoClient:
9
+ def __init__(self, api_key: str):
10
+ base_url = "http://127.0.0.1:4000/graphql"
11
+ self._api_port = RhoApiGraphqlAdapter(base_url=base_url, api_key=api_key)
12
+ self._file_upload_port = UploadFileHttpAdapter()
13
+
14
+ @staticmethod
15
+ def get_table_url(table_id: str, workspace_id: str) -> str:
16
+ base_url = "http://localhost:5173"
17
+ return f"{base_url}/tables/{table_id}?wid={workspace_id}"
18
+
19
+ def store_df(self, data: pd.DataFrame) -> str:
20
+ t1 = time.time()
21
+ url, file_id = self._api_port.get_signed_url()
22
+ t2 = time.time()
23
+ self._file_upload_port.upload_dataframe(url, data)
24
+ t3 = time.time()
25
+ table = self._api_port.process_file(file_id)
26
+ t4 = time.time()
27
+ print("- Get url: ", t2 - t1)
28
+ print("- Upload file: ", t3 - t2)
29
+ print("- Process file: ", t4 - t3)
30
+ print("Total time: ", t4 - t1)
31
+ table_id = table["id"]
32
+ workspace_id = table["workspaceId"]
33
+ return self.get_table_url(table_id, workspace_id)
34
+
35
+ def store_data(self, data: list[dict]) -> str:
36
+ df = pd.DataFrame(data)
37
+ return self.store_df(df)
38
+
39
+ def get_df(self, table_id: str) -> pd.DataFrame:
40
+ data = self.get_data(table_id)
41
+ parsed_data = pd.DataFrame(data)
42
+ if "_id" in parsed_data.columns:
43
+ parsed_data.drop(columns=["_id"], inplace=True)
44
+ return parsed_data
45
+
46
+ def get_data(self, table_id: str) -> list[dict]:
47
+ t1 = time.time()
48
+ data = self._api_port.get_data(table_id)
49
+ t2 = time.time()
50
+ print("Got data in: ", t2 - t1)
51
+ return data
52
+
53
+
54
+ __all__ = ["RhoClient"]
File without changes
@@ -0,0 +1,23 @@
1
+ Date,Account,StockTicker,CUSIP,SecurityName,Shares,Price,MarketValue,Weightings,NetAssets,SharesOutstanding,CreationUnits,MoneyMarketFlag
2
+ 02/28/2023,SPRX,NVDA,67066G104,NVIDIA CORPORATION,1339.00,235.010000,314678.39,11.03%,2853420.000000,200000,8,
3
+ 02/28/2023,SPRX,NET,18915M107,CLOUDFLARE INC,5078.00,60.260000,306000.28,10.72%,2853420.000000,200000,8,
4
+ 02/28/2023,SPRX,ZS,98980G102,ZSCALER INC,1784.00,131.840000,235202.56,8.24%,2853420.000000,200000,8,
5
+ 02/28/2023,SPRX,SNOW,833445109,SNOWFLAKE INC,1492.00,154.650000,230737.80,8.09%,2853420.000000,200000,8,
6
+ 02/28/2023,SPRX,CRWD,22788C105,CROWDSTRIKE HLDGS INC,1645.00,120.650000,198469.25,6.96%,2853420.000000,200000,8,
7
+ 02/28/2023,SPRX,AMZN,023135106,AMAZON COM INC,1803.00,93.760000,169049.28,5.92%,2853420.000000,200000,8,
8
+ 02/28/2023,SPRX,HUBS,443573100,HUBSPOT INC,394.00,388.580000,153100.52,5.37%,2853420.000000,200000,8,
9
+ 02/28/2023,SPRX,SHOP,82509L107,SHOPIFY INC,3632.00,40.480000,147023.36,5.15%,2853420.000000,200000,8,
10
+ 02/28/2023,SPRX,MRVL,573874104,MARVELL TECHNOLOGY INC,2934.00,44.310000,130005.54,4.56%,2853420.000000,200000,8,
11
+ 02/28/2023,SPRX,FCX,35671D857,FREEPORT-MCMORAN INC,3024.00,40.110000,121292.64,4.25%,2853420.000000,200000,8,
12
+ 02/28/2023,SPRX,ZM,98980L101,ZOOM VIDEO COMMUNICATIONS INC CL A,1638.00,73.720000,120753.36,4.23%,2853420.000000,200000,8,
13
+ 02/28/2023,SPRX,ROK,773903109,ROCKWELL AUTOMATION INC,409.00,294.390000,120405.51,4.22%,2853420.000000,200000,8,
14
+ 02/28/2023,SPRX,PANW,697435105,PALO ALTO NETWORKS INC,585.00,188.510000,110278.35,3.86%,2853420.000000,200000,8,
15
+ 02/28/2023,SPRX,U,91332U101,UNITY SOFTWARE INC,3227.00,29.640000,95648.28,3.35%,2853420.000000,200000,8,
16
+ 02/28/2023,SPRX,DDOG,23804L103,DATADOG INC,1165.00,77.600000,90404.00,3.17%,2853420.000000,200000,8,
17
+ 02/28/2023,SPRX,GXO,36262G101,GXO LOGISTICS INCORPORATED,1394.00,48.450000,67539.30,2.37%,2853420.000000,200000,8,
18
+ 02/28/2023,SPRX,ANSS,03662Q105,ANSYS INC,193.00,295.680000,57066.24,2.00%,2853420.000000,200000,8,
19
+ 02/28/2023,SPRX,JOBY,G65163100,JOBY AVIATION INC,10667.00,4.550000,48534.85,1.70%,2853420.000000,200000,8,
20
+ 02/28/2023,SPRX,RIO,767204100,RIO TINTO PLC,685.00,69.160000,47374.60,1.66%,2853420.000000,200000,8,
21
+ 02/28/2023,SPRX,ADSK,052769106,AUTODESK INC,192.00,196.680000,37762.56,1.32%,2853420.000000,200000,8,
22
+ 02/28/2023,SPRX,JD,47215P106,JD.COM INC,800.00,44.740000,35792.00,1.25%,2853420.000000,200000,8,
23
+ 02/28/2023,SPRX,Cash&Other,Cash&Other,Cash & Other,16242.86,1.000000,16242.86,0.57%,2853420.000000,200000,8,Y
@@ -0,0 +1,12 @@
1
+
2
+ class RhoStoreError(Exception):
3
+ """ Base exception """
4
+ pass
5
+
6
+
7
+ class NotFound(Exception):
8
+ pass
9
+
10
+
11
+ class RhoApiError(RhoStoreError):
12
+ pass
@@ -0,0 +1,6 @@
1
+ import os
2
+
3
+
4
+ def get_relative_path(path: str, caller_file: str) -> str:
5
+ base_dir = os.path.dirname(caller_file)
6
+ return os.path.join(base_dir, path)
@@ -0,0 +1 @@
1
+ from rho_store.ports.file_storage_port import *
@@ -0,0 +1,16 @@
1
+ import abc
2
+
3
+ import pandas as pd
4
+
5
+
6
+ class FileStoragePort(metaclass=abc.ABCMeta):
7
+ @abc.abstractmethod
8
+ async def upload_dataframe(self, name: str, data: pd.DataFrame):
9
+ raise NotImplementedError
10
+
11
+ @abc.abstractmethod
12
+ async def download_dataframe(self, name: str) -> pd.DataFrame:
13
+ raise NotImplementedError
14
+
15
+
16
+ __all__ = ["FileStoragePort"]
File without changes