|
| 1 | +import logging |
| 2 | + |
| 3 | +import requests |
| 4 | + |
| 5 | +from substack.exceptions import SubstackAPIException, SubstackRequestException |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | + |
| 10 | +class Api: |
| 11 | + """ |
| 12 | +
|
| 13 | + A python interface into the Substack API |
| 14 | +
|
| 15 | + """ |
| 16 | + |
| 17 | + def __init__(self, email: str, password: str, base_url: str | None = None, debug: bool = False): |
| 18 | + """ |
| 19 | +
|
| 20 | + To create an instance of the substack.Api class: |
| 21 | + >>> import substack |
| 22 | + >>> api = substack.Api(email="substack email", password="substack password") |
| 23 | +
|
| 24 | + Args: |
| 25 | + email: |
| 26 | + password: |
| 27 | + base_url: |
| 28 | + The base URL to use to contact the Substack API. |
| 29 | + Defaults to https://substack.com/api/v1. |
| 30 | + """ |
| 31 | + self.base_url = base_url or "https://substack.com/api/v1" |
| 32 | + |
| 33 | + if debug: |
| 34 | + logging.basicConfig() |
| 35 | + logging.getLogger().setLevel(logging.DEBUG) |
| 36 | + |
| 37 | + self._init_session(email, password) |
| 38 | + |
| 39 | + def login(self, email: str, password: str): |
| 40 | + """ |
| 41 | +
|
| 42 | + Args: |
| 43 | + email: |
| 44 | + password: |
| 45 | + """ |
| 46 | + |
| 47 | + response = self._session.post(f"{self.base_url}/login", json={"captcha_response": None, |
| 48 | + "email": email, |
| 49 | + "for_pub": "", |
| 50 | + "password": password, |
| 51 | + "redirect": "/"}) |
| 52 | + return Api._handle_response(response=response) |
| 53 | + |
| 54 | + def _init_session(self, email, password): |
| 55 | + self._session = requests.Session() |
| 56 | + |
| 57 | + self.login(email, password) |
| 58 | + |
| 59 | + @staticmethod |
| 60 | + def _handle_response(response: requests.Response): |
| 61 | + """ |
| 62 | +
|
| 63 | + Internal helper for handling API responses from the Substack server. |
| 64 | + Raises the appropriate exceptions when necessary; otherwise, returns the |
| 65 | + response. |
| 66 | +
|
| 67 | + """ |
| 68 | + |
| 69 | + if not (200 <= response.status_code < 300): |
| 70 | + raise SubstackAPIException(response.status_code, response.text) |
| 71 | + try: |
| 72 | + return response.json() |
| 73 | + except ValueError: |
| 74 | + raise SubstackRequestException('Invalid Response: %s' % response.text) |
0 commit comments