Skip to content

Commit 47886fd

Browse files
committed
implemented a ratelimiter
1 parent 61269c1 commit 47886fd

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

open_sea_v1/endpoints/client.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
import logging
22
from abc import ABC
33
from dataclasses import dataclass
4-
from typing import Optional, Generator
4+
from typing import Optional, Generator, Union
55

6+
from ratelimit import limits, sleep_and_retry
67
from requests import Response, request
78

89
from open_sea_v1.responses.abc import BaseResponse
910

1011
logger = logging.getLogger(__name__)
1112

13+
MAX_CALLS_PER_SECOND = 2 # gets overriden if API key is passed to ClientParams instance
14+
RATE_LIMIT = 1 # second
15+
1216
@dataclass
1317
class ClientParams:
1418
"""Common OpenSea Endpoint parameters to pass in."""
@@ -21,6 +25,7 @@ class ClientParams:
2125
def __post_init__(self):
2226
self._validate_attrs()
2327
self._decrement_max_pages_attr()
28+
self._set_max_rate_limit()
2429

2530
def _validate_attrs(self) -> None:
2631
if self.limit is not None and not 0 < self.limit <= 300:
@@ -38,14 +43,22 @@ def _decrement_max_pages_attr(self) -> None:
3843
if self.max_pages is not None:
3944
self.max_pages -= 1
4045

46+
def _set_max_rate_limit(self) -> None:
47+
global MAX_CALLS_PER_SECOND
48+
MAX_CALLS_PER_SECOND = 2 # per second
49+
if self.api_key:
50+
raise NotImplementedError("I don't know what the rate limit is for calls with an API key is yet.")
51+
4152

4253
class BaseClient(ABC):
4354
client_params: ClientParams
4455
processed_pages: int = 0
4556
response = None
4657
parsed_http_response = None
4758
url = None
59+
rate_limiting: bool = True
4860
_http_response = None
61+
_rate_limiting_timer: float = 0.0
4962

5063
@property
5164
def http_headers(self) -> dict:
@@ -54,7 +67,10 @@ def http_headers(self) -> dict:
5467
params['headers'] = {'X-API-Key': self.client_params.api_key}
5568
return params
5669

70+
@sleep_and_retry
71+
@limits(calls=MAX_CALLS_PER_SECOND, period=RATE_LIMIT)
5772
def _get_request(self, **kwargs) -> Response:
73+
"""Get requests with a rate limiter."""
5874
updated_kwargs = kwargs | self.http_headers
5975
return request('GET', self.url, **updated_kwargs)
6076

0 commit comments

Comments
 (0)