pelican-port-forwarding/api/__init__.py

51 lines
1.2 KiB
Python
Raw Normal View History

2025-03-02 14:40:53 +00:00
import requests
import enum
from typing import Tuple
class ApiAuthType(enum.Enum):
NoAuth = 0
Header = 1
Cookie = 2
class Api(object):
base_url: str = None
def transform(self, data):
return data
def apply_authentication(self, use_alt_auth: bool = False) -> Tuple[ApiAuthType, dict]:
2025-03-02 14:40:53 +00:00
raise NotImplementedError
def _get(self, endpoint, raw: bool = False):
url = self.base_url + endpoint
headers = {
"Accept": "application/json"
}
cookies = {}
ty, auth = self.apply_authentication()
if ty == ApiAuthType.Header:
headers.update(auth)
elif ty == ApiAuthType.Cookie:
cookies.update(auth)
response = requests.get(url, headers=headers, cookies=cookies)
if response.status_code == 403:
ty, auth = self.apply_authentication(True)
if ty == ApiAuthType.Header:
headers.update(auth)
elif ty == ApiAuthType.Cookie:
cookies.update(auth)
response = requests.get(url, headers=headers, cookies=cookies)
2025-03-02 14:40:53 +00:00
if raw:
return response
return self.transform(response.json())