Skip to content

Commit d2cd650

Browse files
committed
login and session
1 parent 2e67956 commit d2cd650

7 files changed

Lines changed: 122 additions & 0 deletions

File tree

‎requirements.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
requests

‎substack/__init__.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
"""A library that provides a Python interface to the Substack API."""
2+
3+
__author__ = 'Paolo Mazza'
4+
__email__ = 'mazzapaolo2019@gmail.com'
5+
__license__ = 'MIT License'
6+
__version__ = '1.0'
7+
__url__ = 'https://github.com/hogier/python-substack'
8+
__download_url__ = 'https://pypi.python.org/pypi/python-substack'
9+
__description__ = 'A Python wrapper around the Substack API'
10+
11+
from .api import Api

‎substack/api.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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)

‎substack/exceptions.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import json
2+
3+
4+
class SubstackAPIException(Exception):
5+
6+
def __init__(self, status_code, text):
7+
try:
8+
json_res = json.loads(text)
9+
except ValueError:
10+
self.message = f'Invalid JSON error message from Substack: {text}'
11+
else:
12+
self.message = ", ".join(list(map(lambda error: error.get("msg", ""), json_res.get("errors", []))))
13+
self.message = self.message or json_res.get("error", "")
14+
self.status_code = status_code
15+
16+
def __str__(self):
17+
return f'APIError(code={self.status_code}): {self.message}'
18+
19+
20+
class SubstackRequestException(Exception):
21+
def __init__(self, message):
22+
self.message = message
23+
24+
def __str__(self):
25+
return f'SubstackRequestException: {self.message}'
File renamed without changes.

‎tests/substack/__init__.py‎

Whitespace-only changes.

‎tests/substack/test_api.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import unittest
2+
3+
from substack import Api
4+
from substack.exceptions import SubstackAPIException
5+
6+
7+
class ApiTest(unittest.TestCase):
8+
9+
def test_api_exception(self):
10+
with self.assertRaises(SubstackAPIException):
11+
Api(email="", password="")

0 commit comments

Comments
 (0)