Skip to content

Commit 46d7374

Browse files
authored
Make RESTful client a context manager and update example code (#37)
1 parent f5b98ad commit 46d7374

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

polygon/rest/client.py

+9
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,15 @@ def __init__(self, auth_key: str):
1717
self._session = requests.Session()
1818
self._session.params["apiKey"] = self.auth_key
1919

20+
def __enter__(self):
21+
return self
22+
23+
def __exit__(self, *args):
24+
self.close()
25+
26+
def close(self):
27+
self._session.close()
28+
2029
def _handle_response(self, response_type: str, endpoint: str, params: Dict[str, str]) -> Type[models.AnyDefinition]:
2130
resp: requests.Response = self._session.get(endpoint, params=params)
2231
if resp.status_code == 200:

rest-example.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33

44
def main():
55
key = "your api key"
6-
client = RESTClient(key)
76

8-
resp = client.stocks_equities_daily_open_close("AAPL", "2018-03-02")
9-
print(f"On: {resp.from_} Apple opened at {resp.open} and closed at {resp.close}")
7+
# RESTClient can be used as a context manager to facilitate closing the underlying http session
8+
# https://requests.readthedocs.io/en/master/user/advanced/#session-objects
9+
with RESTClient(key) as client:
10+
resp = client.stocks_equities_daily_open_close("AAPL", "2018-03-02")
11+
print(f"On: {resp.from_} Apple opened at {resp.open} and closed at {resp.close}")
1012

1113

1214
if __name__ == '__main__':

0 commit comments

Comments
 (0)