Skip to content

Commit

Permalink
Fixed attribute error and added annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
drewxa authored and drewxa committed Nov 15, 2023
1 parent 8aaeac3 commit 162a5ab
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 39 deletions.
7 changes: 4 additions & 3 deletions ad_api/api/dsp/client.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from typing import Dict
from ad_api.base import Client


class DspClient(Client):
@property
def headers(self):
def headers(self) -> Dict[str, str]:
return {
'User-Agent': self.user_agent,
'Amazon-Advertising-API-ClientId': self.credentials.client_id,
'Authorization': 'Bearer %s' % self.auth.access_token,
'Amazon-Advertising-API-ClientId': self.credentials['client_id'],
'Authorization': f'Bearer {self.auth.access_token}',
'Content-Type': 'application/json',
}
31 changes: 16 additions & 15 deletions ad_api/base/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,24 @@
from urllib.parse import urlparse, quote
from ad_api.base.credential_provider import CredentialProvider
import ad_api.version as vd
from typing import Any, Dict, Optional

log = logging.getLogger(__name__)
role_cache = TTLCache(maxsize=int(os.environ.get('AD_API_AUTH_CACHE_SIZE', 10)), ttl=3200)
_DEFAULT_MARKETPLACE = Marketplaces[os.environ['AD_API_DEFAULT_MARKETPLACE']] if 'AD_API_DEFAULT_MARKETPLACE' in os.environ else Marketplaces.EU


class Client(BaseClient):
def __init__(
self,
account='default',
marketplace: Marketplaces = Marketplaces[os.environ['AD_API_DEFAULT_MARKETPLACE']] if 'AD_API_DEFAULT_MARKETPLACE' in os.environ else Marketplaces.EU,
credentials=None,
proxies=None,
verify=True,
timeout=None,
debug=False,
access_token=None,
account: str = 'default',
marketplace: Marketplaces = _DEFAULT_MARKETPLACE,
credentials: Optional[Dict[str, str]] = None,
proxies: Optional[Dict[str, str]] = None,
verify: bool = True,
timeout: Optional[int] = None,
debug: bool = False,
access_token: Optional[str] = None,
):
self.credentials = CredentialProvider(account, credentials).credentials
self._auth = AccessTokenClient(
Expand All @@ -52,7 +54,7 @@ def __init__(
self.user_agent += f'-{version}'

@property
def headers(self):
def headers(self) -> Dict[str, str]:
return {
'User-Agent': self.user_agent,
'Amazon-Advertising-API-ClientId': self.credentials['client_id'],
Expand All @@ -66,7 +68,7 @@ def auth(self) -> AccessTokenResponse:
return self._auth.get_auth() if self._access_token is None else AccessTokenResponse(access_token=self._access_token)

@staticmethod
def _download(self, params: dict = None, headers=None) -> ApiResponse:
def _download(self: Any, params: Optional[dict] = None, headers: Optional[dict] = None) -> ApiResponse:
location = params.get("url")

try:
Expand Down Expand Up @@ -208,9 +210,9 @@ def _download(self, params: dict = None, headers=None) -> ApiResponse:
def _request(
self,
path: str,
data: str = None,
params: dict = None,
headers=None,
data: Optional[str] = None,
params: Optional[dict] = None,
headers: Optional[dict] = None,
) -> ApiResponse:
if params is None:
params = {}
Expand Down Expand Up @@ -259,7 +261,7 @@ def _request(
return self._check_response(res)

@staticmethod
def _check_response(res) -> ApiResponse:
def _check_response(res: requests.Response) -> ApiResponse:
headers = vars(res).get('headers')
status_code = vars(res).get('status_code')

Expand Down Expand Up @@ -291,4 +293,3 @@ def _check_response(res) -> ApiResponse:
js = res.content

raise exception(status_code, js, headers)
exit(res.status_code)
36 changes: 15 additions & 21 deletions ad_api/base/credential_provider.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import abc
import os

from typing import Dict, Optional
from typing import Any, Dict, Optional

import confuse
import logging
Expand All @@ -19,19 +19,19 @@ class MissingCredentials(Exception):


class BaseCredentialProvider(abc.ABC):
def __init__(self, credentials: dict or str, *args, **kwargs):
def __init__(self, credentials: Dict[str, str], *args: Any, **kwargs: Any):
self.credentials = credentials

@abc.abstractmethod
def load_credentials(self):
def load_credentials(self) -> Dict[str, str]:
pass

def _get_env(self, key):
return os.environ.get(f'{key}', os.environ.get(key))
def _get_env(self, key: str) -> str:
return os.environ.get(key)

def check_credentials(self):
def check_credentials(self) -> Dict[str, str]:
try:
self.errors = [c for c in required_credentials if c not in self.credentials.keys() or not self.credentials[c]]
self.errors = [c for c in required_credentials if c not in self.credentials or not self.credentials[c]]
except (AttributeError, TypeError):
raise MissingCredentials(f'Credentials are missing: {", ".join(required_credentials)}')
if not len(self.errors):
Expand All @@ -40,10 +40,10 @@ def check_credentials(self):


class FromEnvCredentialProvider(BaseCredentialProvider):
def __init__(self, *args, **kwargs):
def __init__(self, *args: Any, **kwargs: Any):
pass

def load_credentials(self):
def load_credentials(self) -> Dict[str, str]:
account_data = dict(
refresh_token=self._get_env('AD_API_REFRESH_TOKEN'),
client_id=self._get_env('AD_API_CLIENT_ID'),
Expand All @@ -54,26 +54,23 @@ def load_credentials(self):
self.check_credentials()
return self.credentials

def _get_env(self, key):
return os.environ.get(f'{key}', os.environ.get(key))


class FromCodeCredentialProvider(BaseCredentialProvider):
def __init__(self, credentials: dict, *args, **kwargs):
def __init__(self, credentials: Dict, *args: Any, **kwargs: Any):
super().__init__(credentials)

def load_credentials(self):
def load_credentials(self) -> Dict[str, str]:
self.check_credentials()
return self.credentials


class FromConfigFileCredentialProvider(BaseCredentialProvider):
file = 'credentials.yml' # Will moved to default confuse config.yaml

def __init__(self, account: str, *args, **kwargs):
def __init__(self, account: str, *args: Any, **kwargs: Any):
self.account = account

def load_credentials(self):
def load_credentials(self) -> Dict[str, str]:
try:
config = confuse.Configuration('python-ad-api')
config_filename = os.path.join(config.config_dir(), self.file)
Expand All @@ -94,10 +91,7 @@ def load_credentials(self):


class CredentialProvider:
def load_credentials(self):
pass

def _get_env(self, key):
def _get_env(self, key: str) -> Optional[str]:
return os.environ.get(f'{key}', os.environ.get(key))

def __init__(
Expand Down Expand Up @@ -134,7 +128,7 @@ def __init__(
logging.error(MissingCredentials)

class Config:
def __init__(self, **kwargs):
def __init__(self, **kwargs: Any):
self.refresh_token = kwargs.get('refresh_token')
self.client_id = kwargs.get('client_id')
self.client_secret = kwargs.get('client_secret')
Expand Down

0 comments on commit 162a5ab

Please sign in to comment.