Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions shipengine_sdk/errors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,22 @@ def __init__(

def _are_enums_valid(self):
if self.source is None:
return self
pass # noqa
elif not does_member_value_exist(self.source, ErrorSource):
raise ValueError(
f"Error source must be a member of ErrorSource enum - [{self.source}] provided."
)

if self.error_type is None:
return self
pass # noqa
elif not does_member_value_exist(self.error_type, ErrorType):
raise ValueError(
f"Error type must be a member of ErrorType enum - [{self.error_type}] provided."
)

if self.error_code is None:
return self
elif self.error_code not in (member.value for member in ErrorCode):
pass # noqa
elif not does_member_value_exist(self.error_code, ErrorCode):
raise ValueError(
f"Error type must be a member of ErrorCode enum - [{self.error_code}] provided."
)
Expand Down
12 changes: 6 additions & 6 deletions shipengine_sdk/http_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import json
import os
import platform
from typing import Dict, Optional
from typing import Any, Dict, Optional

import requests
from requests import PreparedRequest, Request, RequestException, Response, Session
Expand Down Expand Up @@ -37,8 +37,8 @@ def __init__(self) -> None:
self.session = requests.session()

def send_rpc_request(
self, method: str, params: Optional[Dict[str, any]], retry: int, config: ShipEngineConfig
) -> Dict[str, any]:
self, method: str, params: Optional[Dict[str, Any]], retry: int, config: ShipEngineConfig
) -> Dict[str, Any]:
"""
Send a `JSON-RPC 2.0` request via HTTP Messages to ShipEngine API. If the response
* is successful, the result is returned. Otherwise, an error is thrown.
Expand All @@ -53,13 +53,13 @@ def send_rpc_request(
else os.getenv("CLIENT_BASE_URI")
)

request_headers: Dict[str, any] = {
request_headers: Dict[str, Any] = {
"User-Agent": self._derive_user_agent(),
"Content-Type": "application/json",
"Accept": "application/json",
}

request_body: Dict[str, any] = wrap_request(method=method, params=params)
request_body: Dict[str, Any] = wrap_request(method=method, params=params)

req: Request = Request(
method="POST",
Expand All @@ -80,7 +80,7 @@ def send_rpc_request(
error_code=ErrorCode.UNSPECIFIED.value,
)

resp_body: Dict[str, any] = resp.json()
resp_body: Dict[str, Any] = resp.json()
status_code: int = resp.status_code

is_response_404(status_code=status_code, response_body=resp_body, config=config)
Expand Down
14 changes: 8 additions & 6 deletions shipengine_sdk/jsonrpc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
functionality for sending HTTP requests from the ShipEngine SDK.
"""
import time
from typing import Dict, Optional
from typing import Any, Dict, Optional

from ..errors import RateLimitExceededError
from ..http_client import ShipEngineClient
Expand All @@ -12,22 +12,24 @@


def rpc_request(
method: str, config: ShipEngineConfig, params: Optional[Dict[str, any]] = None
) -> Dict[str, any]:
method: str, config: ShipEngineConfig, params: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Create and send a `JSON-RPC 2.0` request over HTTP messages.
TODO: add param and return docs
"""
return rpc_request_loop(method, params, config)


def rpc_request_loop(method: str, params: dict, config: ShipEngineConfig) -> Dict[str, any]:
def rpc_request_loop(
method: str, params: Optional[Dict[str, Any]], config: ShipEngineConfig
) -> Dict[str, Any]:
client: ShipEngineClient = ShipEngineClient()
api_response: Optional[Dict[str, any]] = None
api_response: Optional[Dict[str, Any]] = None
retry: int = 0
while retry <= config.retries:
try:
api_response: Dict[str, any] = client.send_rpc_request(
api_response = client.send_rpc_request(
method=method, params=params, retry=retry, config=config
)
except Exception as err:
Expand Down
12 changes: 6 additions & 6 deletions shipengine_sdk/jsonrpc/process_request.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Functions that help with process requests and handle responses."""
from typing import Dict, Optional
from typing import Any, Dict, Optional
from uuid import uuid4

from ..errors import (
Expand All @@ -13,15 +13,15 @@
from ..models import ErrorType


def wrap_request(method: str, params: Optional[Dict[str, any]]) -> Dict[str, any]:
def wrap_request(method: str, params: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""
Wrap request per `JSON-RPC 2.0` spec.

:param str method: The RPC Method to be sent to the RPC Server to
invoke a specific remote procedure.
:param params: The request data for the RPC request. This argument
is optional and can either be a dictionary or None.
:type params: Optional[Dict[str, any]]
:type params: Optional[Dict[str, Any]]
"""
if params is None:
return dict(id=f"req_{str(uuid4()).replace('-', '')}", jsonrpc="2.0", method=method)
Expand All @@ -31,13 +31,13 @@ def wrap_request(method: str, params: Optional[Dict[str, any]]) -> Dict[str, any
)


def handle_response(response_body: Dict[str, any]) -> Dict[str, any]:
def handle_response(response_body: Dict[str, Any]) -> Dict[str, Any]:
"""Handles the response from ShipEngine API."""
if "result" in response_body:
return response_body

error: Dict[str, any] = response_body["error"]
error_data: Dict[str, any] = error["data"]
error: Dict[str, Any] = response_body["error"]
error_data: Dict[str, Any] = error["data"]
error_type: str = error_data["type"]
if error_type is ErrorType.ACCOUNT_STATUS.value:
raise AccountStatusError(
Expand Down
17 changes: 8 additions & 9 deletions shipengine_sdk/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"""ShipEngine SDK Models & Enumerations"""
from .address import Address, AddressValidateResult
from .carriers import Carrier, CarrierAccount
from .enums import (
CarrierNames,
Carriers,
Country,
Endpoints,
ErrorCode,
ErrorSource,
ErrorType,
RPCMethods,
from .enums import * # noqa
from .track_pacakge import (
Location,
Package,
Shipment,
TrackingEvent,
TrackingQuery,
TrackPackageResult,
)
32 changes: 2 additions & 30 deletions shipengine_sdk/models/carriers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,10 @@
"""CarrierAccount class object and immutable carrier object."""
import json
from typing import Dict
from typing import Any, Dict

from ...errors import InvalidFieldValueError, ShipEngineError
from ..enums import Carriers, does_member_value_exist, get_carrier_name_value

# @dataclass_json(letter_case=LetterCase.CAMEL)
# @dataclass(frozen=True)
# class Carrier:
# """This immutable class object represents a given Carrier provider e.g. `FedEx`, `UPS`, `USPS`."""
# name: str
# code: str
#
# def __post_init__(self) -> None:
# """An immutable Carrier object. e.g. `FedEx`, `UPS`, `USPS`."""
# if not does_member_value_exist(self.name, CarrierNames):
# raise ShipEngineError(f"Carrier [{self.name}] not currently supported.")
#
# if not does_member_value_exist(self.code, Carriers):
# raise ShipEngineError(f"Carrier [{self.code}] not currently supported.")
#
#
# @dataclass_json(letter_case=LetterCase.CAMEL)
# @dataclass(frozen=True)
# class CarrierAccount:
# """This class represents a given account with a Carrier provider e.g. `FedEx`, `UPS`, `USPS`."""
# carrier: Union[str, Carrier]
# account_id: str
# account_number: str
# name: str
#
# def __post_init__(self) -> None:
# if not does_member_value_exist()


class Carrier:
def __init__(self, code: str) -> None:
Expand All @@ -53,7 +25,7 @@ def to_json(self):
class CarrierAccount:
carrier: Carrier

def __init__(self, account_information: Dict[str, any]) -> None:
def __init__(self, account_information: Dict[str, Any]) -> None:
"""This class represents a given account with a Carrier provider e.g. `FedEx`, `UPS`, `USPS`."""
self._set_carrier(account_information["carrierCode"])
self.account_id = account_information["accountID"]
Expand Down
1 change: 1 addition & 0 deletions shipengine_sdk/models/enums/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from .error_code import ErrorCode
from .error_source import ErrorSource
from .error_type import ErrorType
from .regex_patterns import RegexPatterns


class Endpoints(Enum):
Expand Down
7 changes: 7 additions & 0 deletions shipengine_sdk/models/enums/regex_patterns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""Enumeration of Regular Expression patterns used in the ShipEngine SDK."""
from enum import Enum


class RegexPatterns(Enum):
VALID_ISO_STRING = r"^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$" # noqa
VALID_ISO_STRING_NO_TZ = r"^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?([+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$" # noqa
Loading