This repository has been archived by the owner on Jan 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcore.py
78 lines (58 loc) · 2.5 KB
/
core.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
68
69
70
71
72
73
74
75
76
77
78
from pprint import pprint
from typing import List, Optional
import humps
from aiohttp import ClientSession
from cachetools import LRUCache, TTLCache
from nepse.errors import NotFound, SymbolOrIdNotPassed
from nepse.security.decorators import is_cached
from nepse.security.types import BaseSecurity, SecurityResponse
BASE_URL = "https://newweb.nepalstock.com/api/nots/security/"
class SecurityClient:
def __init__(self, session: ClientSession) -> None:
self._session = session
self._securities_basic_cache = LRUCache(1000)
self._securities_full_cache = TTLCache(100, 500)
def create_security_model(self, model: BaseSecurity) -> None:
self._securities_basic_cache[model.symbol] = model
def get_security_model(self, symbol: str) -> BaseSecurity:
return self._securities_basic_cache.get(symbol)
def create_security_cache(self, model: SecurityResponse) -> None:
self._securities_full_cache[model.security_id] = model
def get_security_cache(self, security_id: int) -> SecurityResponse:
return self._securities_full_cache.get(security_id)
async def _update_basic_securities_cache(self) -> None:
await self.fetch_all_base_securities()
async def fetch_all_base_securities(self) -> List[BaseSecurity]:
securities = await (await self._session.get(BASE_URL)).json()
def create_security_object(security: dict):
data = humps.decamelize(security)
model = BaseSecurity(**data)
self.create_security_model(model)
return model
securities_objects = [
create_security_object(security) for security in securities
]
return securities_objects
@is_cached
async def get_security_response(
self, id: Optional[int], symbol: Optional[str]
) -> SecurityResponse:
if not any(id or symbol):
raise SymbolOrIdNotPassed()
if not id:
model = self.get_security_model(symbol)
if not model:
raise NotFound()
id = model.id
model = self.get_security_cache(id)
if not model:
model = await self.fetch_security_response(id)
return model
async def fetch_security_response(self, id: int):
data = await (await self._session.get(f"{BASE_URL}/{id}")).json()
if not data:
raise NotFound()
data = humps.decamelize(data)
model = SecurityResponse(**data)
self.create_security_cache(model)
return model