Skip to content

Commit 4c6ada8

Browse files
Merge pull request #20 from unniznd/feature_get_balance
feature: getBalance API added and tested successfully
2 parents 05c3200 + ca871b6 commit 4c6ada8

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

src/lighthouseweb3/__init__.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
deal_status,
88
get_uploads as getUploads,
99
download as _download,
10-
get_file_info as getFileInfo
10+
get_file_info as getFileInfo,
11+
get_balance as getBalance
1112
)
1213

1314

@@ -44,6 +45,17 @@ def uploadBlob(self, source: io.BufferedReader, filename: str, tag: str = ''):
4445
return d.uploadBlob(source, filename, self.token, tag)
4546
except Exception as e:
4647
raise e
48+
49+
def getBalance(self):
50+
"""
51+
Retrieve the balance information of a user from the Lighthouse.
52+
:param publicKey: str, The public key of the user.
53+
:return: dict[str, any], A dictionary containing the data usage and data limit details.
54+
"""
55+
try:
56+
return getBalance.get_balance(self.token)
57+
except Exception as e:
58+
raise e
4759

4860
@staticmethod
4961
def downloadBlob(dist: io.BufferedWriter, cid: str, chunk_size=1024*1024*10):
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from .config import Config
2+
import requests as req
3+
4+
def get_balance(token:str):
5+
headers = {
6+
"Authorization": f"Bearer {token}",
7+
}
8+
url = f"{Config.lighthouse_api}/api/user/user_data_usage"
9+
try:
10+
response = req.get(url, headers=headers)
11+
except Exception as e:
12+
raise Exception("Failed to get account balance")
13+
14+
return response.json()

tests/test_get_balance.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import unittest
4+
from src.lighthouseweb3 import Lighthouse
5+
from .setup import parse_env
6+
7+
8+
class TestGetBalance(unittest.TestCase):
9+
10+
def test_get_balance(self):
11+
"""test get_balance function"""
12+
parse_env()
13+
l = Lighthouse(os.environ.get("LIGHTHOUSE_TOKEN"))
14+
res = l.getBalance()
15+
self.assertIsInstance(res, dict, "data is a dict")
16+
self.assertIsInstance(res.get("dataLimit"), int, "data limit is a integer")
17+
self.assertIsInstance(res.get("dataUsed"), int, "data used is a integer")
18+
19+
def test_get_balance_invalid_token(self):
20+
"""test get_balance function with invalid token"""
21+
parse_env()
22+
l = Lighthouse('invalid_token')
23+
res = l.getBalance()
24+
self.assertIsInstance(res, dict, "res is a dict")
25+
self.assertIn("authentication failed", str(res).lower())
26+

0 commit comments

Comments
 (0)