Skip to content

Instantly share code, notes, and snippets.

@bl4ckst0ne
bl4ckst0ne / flask_pynamodb_get_connection.py
Created January 6, 2021 21:45
Overridden get connection method
@classmethod
def _get_connection(cls) -> TableConnection:
meta = getattr(cls, "Meta", None)
if not meta or cls._connection:
return super()._get_connection()
for key, value in cls._app_config.items():
if not getattr(meta, key, None):
setattr(meta, key, value)
@bl4ckst0ne
bl4ckst0ne / pynamodb_get_connection.py
Created January 6, 2021 21:40
get_connection function from pynamodb.Models.Model class
@classmethod
def _get_connection(cls) -> TableConnection:
"""
Returns a (cached) connection
"""
if not hasattr(cls, "Meta"):
raise AttributeError(
'As of v1.0 PynamoDB Models require a `Meta` class.\n'
'Model: {}.{}\n'
'See https://pynamodb.readthedocs.io/en/latest/release_notes.html\n'.format(
@bl4ckst0ne
bl4ckst0ne / flask_pynamodb_manager.py
Created January 6, 2021 21:35
Flask-PynamoDB manager class
class PynamoDB:
Model = ModelClass
def __init__(self, app: Flask = None):
self.app = app
if app:
self.init_app(app)
def init_app(self, app: Flask):
@bl4ckst0ne
bl4ckst0ne / rest_client.py
Created November 3, 2020 09:44
Generic REST API client
from functools import partialmethod
from typing import Union, Dict, List, Any
import requests
JSONType = Union[None, bool, int, float, str, List[Any], Dict[str, Any]]
class RestError(Exception):
"""
@bl4ckst0ne
bl4ckst0ne / github_client_properties.py
Created November 3, 2020 09:30
Properties for GitHub Client
class GitHubClient:
BASE_URL = 'https://api.github.com'
def __init__(self, username: str, token: str, headers: Dict[str, str] = None):
self._session = requests.Session()
self._session.auth = requests.auth.HTTPBasicAuth(username, token)
self._session.headers = headers or GITHUB_DEFAULT_HEADERS
@property
def username(self) -> str:
@bl4ckst0ne
bl4ckst0ne / github_client_context_managers.py
Created November 3, 2020 09:28
Context Managers for GitHub Client
class GitHubClient:
BASE_URL = 'https://api.github.com'
def __init__(self, username: str, token: str, headers: Dict[str, str] = None):
self._session = requests.Session()
self._session.auth = requests.auth.HTTPBasicAuth(username, token)
self._session.headers = headers or GITHUB_DEFAULT_HEADERS
def __enter__(self):
return self
@bl4ckst0ne
bl4ckst0ne / github_client.py
Last active November 3, 2020 09:25
GitHub REST API integration: client
from typing import Union, Dict, List, Any
import requests
GITHUB_DEFAULT_HEADERS = {'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'python-requests'}
JSONType = Union[None, bool, int, float, str, List[Any], Dict[str, Any]]
class GitHubError(Exception):
@bl4ckst0ne
bl4ckst0ne / get_user_and_repos_dry.py
Last active November 3, 2020 10:34
Improved version for GitHub REST API integration: DRY
def get(path: str, **kwargs) -> JSONType:
kwargs['headers'] = {**HEADERS, **kwargs.get('headers', {})}
kwargs['auth'] = kwargs.get('auth', AUTH)
try:
resp = requests.get(f'{BASE_URL}/{path}', **kwargs)
resp.raise_for_status()
return resp.json()
except requests.HTTPError as http_error:
raise GitHubError(f'Invalid request from GitHub API: {http_error}') from http_error
@bl4ckst0ne
bl4ckst0ne / get_user_and_repos.py
Created November 3, 2020 09:04
REST API Integration for GitHub: get repos, and user's details
from typing import Dict, List, Any
import requests
BASE_URL = 'https://api.github.com'
USERNAME = '<USERNAME>'
ACCESS_TOKEN = '<TOKEN>'
AUTH = USERNAME, ACCESS_TOKEN
HEADERS = {'Accept': 'application/vnd.github.v3+json'}
@bl4ckst0ne
bl4ckst0ne / get_public_repos_improved.py
Created November 3, 2020 09:01
Improved version of the GitHub REST API integration
from typing import Dict, List, Any
import requests
BASE_URL = 'https://api.github.com'
USERNAME = '<USERNAME>'
ACCESS_TOKEN = '<TOKEN>'
AUTH = USERNAME, ACCESS_TOKEN
HEADERS = {'Accept': 'application/vnd.github.v3+json'}