Skip to content

Instantly share code, notes, and snippets.

@cdunklau
Created March 4, 2020 21:25
Show Gist options
  • Save cdunklau/a732e44a7585a49ca2656d9a23526932 to your computer and use it in GitHub Desktop.
Save cdunklau/a732e44a7585a49ca2656d9a23526932 to your computer and use it in GitHub Desktop.
Alternative constructors with @classmethod
import requests
class QuotesAPIClient:
def __init__(self, baseurl, session):
self._baseurl = baseurl
self._session = session
@classmethod
def default(cls, api_token):
session = requests.Session()
session.headers['Authorization'] = f'bearer {api_token}'
session.headerr['Accept'] = 'application/json'
return cls(baseurl='https://quotes.example.com/api', session=session)
def get_all(self):
url = self._baseurl + '/quotes'
r = self._session.get(url)
r.raise_for_status()
return r.json()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment