Skip to content
This repository has been archived by the owner on Jan 13, 2023. It is now read-only.

Commit

Permalink
PR review changes
Browse files Browse the repository at this point in the history
  • Loading branch information
lzpap committed Mar 20, 2020
1 parent 9c95b9c commit 0e609ad
Show file tree
Hide file tree
Showing 46 changed files with 259 additions and 284 deletions.
2 changes: 1 addition & 1 deletion examples/send_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
Tag,
TryteString,
)
from address_generator import get_seed, output_seed
from .address_generator import get_seed, output_seed


def main(address, depth, message, tag, uri, value):
Expand Down
5 changes: 2 additions & 3 deletions iota/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from typing import Dict

# Define a few magic constants.
from typing import Dict, Text

DEFAULT_PORT: int = 14265
"""
Default port to use when configuring an adapter, if the port is not
Expand All @@ -16,7 +15,7 @@
In that way, it's kind of like toxic waste in a superhero story.
"""

STANDARD_UNITS: Dict[Text, int] = {
STANDARD_UNITS: Dict[str, int] = {
# Valid IOTA unit suffixes. Example value '-273.15 Ki'
'i': 1,
'Ki': 1000,
Expand Down
54 changes: 27 additions & 27 deletions iota/adapter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from inspect import isabstract as is_abstract
from logging import DEBUG, Logger
from socket import getdefaulttimeout as get_default_timeout
from typing import Container, Dict, List, Optional, Text, Tuple, Union, Any
from httpx import AsyncClient, Response, codes, auth
from typing import Container, List, Optional, Tuple, Union, Any, Dict
from httpx import AsyncClient, Response, codes, BasicAuth
import asyncio

from iota.exceptions import with_context
Expand All @@ -32,7 +32,7 @@
"""

# Custom types for type hints and docstrings.
AdapterSpec = Union[Text, 'BaseAdapter']
AdapterSpec = Union[str, 'BaseAdapter']
"""
Placeholder that means “URI or adapter instance”.
Expand Down Expand Up @@ -69,7 +69,7 @@ class InvalidUri(ValueError):
pass


adapter_registry: Dict[Text, 'AdapterMeta'] = {}
adapter_registry: Dict[str, 'AdapterMeta'] = {}
"""
Keeps track of available adapters and their supported protocols.
"""
Expand Down Expand Up @@ -127,7 +127,7 @@ def __init__(cls, what, bases=None, dict=None) -> None:
# adapters.
adapter_registry.setdefault(protocol, cls)

def configure(cls, parsed: Union[Text, SplitResult]) -> 'HttpAdapter':
def configure(cls, parsed: Union[str, SplitResult]) -> 'HttpAdapter':
"""
Creates a new instance using the specified URI.
Expand All @@ -144,7 +144,7 @@ class BaseAdapter(object, metaclass=AdapterMeta):
Adapters make it easy to customize the way an API instance
communicates with a node.
"""
supported_protocols: Tuple[Text] = ()
supported_protocols: Tuple[str] = ()
"""
Protocols that ``resolve_adapter`` can use to identify this adapter
type.
Expand All @@ -157,7 +157,7 @@ def __init__(self) -> None:
self.local_pow: bool = False

@abstract_method
def get_uri(self) -> Text:
def get_uri(self) -> str:
"""
Returns the URI that this adapter will use.
"""
Expand All @@ -166,7 +166,7 @@ def get_uri(self) -> Text:
)

@abstract_method
def send_request(self, payload: Dict, **kwargs: Any) -> Dict:
def send_request(self, payload: dict, **kwargs: Any) -> dict:
"""
Sends an API request to the node.
Expand Down Expand Up @@ -199,7 +199,7 @@ def set_logger(self, logger: Logger) -> 'BaseAdapter':
def _log(
self,
level: int,
message: Text,
message: str,
context: Optional[dict] = None
) -> None:
"""
Expand Down Expand Up @@ -231,7 +231,7 @@ class HttpAdapter(BaseAdapter):
:param Optional[int] timeout:
Connection timeout in seconds.
:param Optional[Tuple(Text,Text)] authentication:
:param Optional[Tuple(str,str)] authentication:
Credetentials for basic authentication with the node.
:return:
Expand Down Expand Up @@ -261,9 +261,9 @@ class HttpAdapter(BaseAdapter):

def __init__(
self,
uri: Union[Text, SplitResult],
uri: Union[str, SplitResult],
timeout: Optional[int] = None,
authentication: Optional[Tuple[Text, Text]] = None
authentication: Optional[Tuple[str, str]] = None
) -> None:
super(HttpAdapter, self).__init__()

Expand Down Expand Up @@ -316,16 +316,16 @@ def __init__(
self.uri = uri

@property
def node_url(self) -> Text:
def node_url(self) -> str:
"""
Returns the node URL.
"""
return self.uri.geturl()

def get_uri(self) -> Text:
def get_uri(self) -> str:
return self.uri.geturl()

async def send_request(self, payload: Dict, **kwargs: Any) -> Dict:
async def send_request(self, payload: dict, **kwargs: Any) -> dict:
kwargs.setdefault('headers', {})
for key, value in self.DEFAULT_HEADERS.items():
kwargs['headers'].setdefault(key, value)
Expand All @@ -343,9 +343,9 @@ async def send_request(self, payload: Dict, **kwargs: Any) -> Dict:

async def _send_http_request(
self,
url: Text,
payload: Optional[Text],
method: Text = 'post',
url: str,
payload: Optional[str],
method: str = 'post',
**kwargs: Any
) -> Response:
"""
Expand All @@ -360,7 +360,7 @@ async def _send_http_request(
)

if self.authentication:
kwargs.setdefault('auth', auth.BasicAuth(*self.authentication))
kwargs.setdefault('auth', BasicAuth(*self.authentication))

self._log(
level=DEBUG,
Expand Down Expand Up @@ -405,9 +405,9 @@ async def _send_http_request(
def _interpret_response(
self,
response: Response,
payload: Dict,
payload: dict,
expected_status: Container[int]
) -> Dict:
) -> dict:
"""
Interprets the HTTP response from the node.
Expand Down Expand Up @@ -437,7 +437,7 @@ def _interpret_response(
)

try:
decoded: Dict = json.loads(raw_content)
decoded: dict = json.loads(raw_content)
# :bc: py2k doesn't have JSONDecodeError
except ValueError:
raise with_context(
Expand Down Expand Up @@ -538,13 +538,13 @@ def configure(cls, uri):
def __init__(self) -> None:
super(MockAdapter, self).__init__()

self.responses: Dict[Text, deque] = {}
self.responses: Dict[str, deque] = {}
self.requests: List[dict] = []

def get_uri(self) -> Text:
def get_uri(self) -> str:
return 'mock://'

def seed_response(self, command: Text, response: Dict) -> 'MockAdapter':
def seed_response(self, command: str, response: dict) -> 'MockAdapter':
"""
Sets the response that the adapter will return for the specified
command.
Expand All @@ -558,7 +558,7 @@ def seed_response(self, command: Text, response: Dict) -> 'MockAdapter':
have a seeded response for a particular command, it will raise a
``BadApiResponse`` exception (simulates a 404 response).
:param Text command:
:param str command:
The name of the command. Note that this is the camelCase version
of the command name (e.g., ``getNodeInfo``, not ``get_node_info``).
Expand All @@ -584,7 +584,7 @@ def seed_response(self, command: Text, response: Dict) -> 'MockAdapter':
self.responses[command].append(response)
return self

async def send_request(self, payload: Dict, **kwargs: Any) -> Dict:
async def send_request(self, payload: Dict, **kwargs: Any) -> dict:
"""
Mimic asynchronous behavior of `HttpAdapter.send_request`.
"""
Expand Down
16 changes: 8 additions & 8 deletions iota/adapter/wrappers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from abc import ABCMeta, abstractmethod as abstract_method
from typing import Dict, Text
from typing import Dict, Any

from iota.adapter import AdapterSpec, BaseAdapter, resolve_adapter

Expand All @@ -22,11 +22,11 @@ def __init__(self, adapter: AdapterSpec) -> None:

self.adapter: BaseAdapter = adapter

def get_uri(self) -> Text:
def get_uri(self) -> str:
return self.adapter.get_uri()

@abstract_method
def send_request(self, payload: Dict, **kwargs: Any) -> Dict:
def send_request(self, payload: dict, **kwargs: Any) -> dict:
raise NotImplementedError(
'Not implemented in {cls}.'.format(cls=type(self).__name__),
)
Expand Down Expand Up @@ -94,13 +94,13 @@ def __init__(self, default_adapter: AdapterSpec) -> None:
# when resolving URIs.
self.adapter_aliases: Dict[AdapterSpec, BaseAdapter] = {}

self.routes: Dict[Text, BaseAdapter] = {}
self.routes: Dict[str, BaseAdapter] = {}

def add_route(self, command: Text, adapter: AdapterSpec) -> 'RoutingWrapper':
def add_route(self, command: str, adapter: AdapterSpec) -> 'RoutingWrapper':
"""
Adds a route to the wrapper.
:param Text command:
:param str command:
The name of the command. Note that this is the camelCase version of
the command name (e.g., ``attachToTangle``, not ``attach_to_tangle``).
Expand All @@ -125,13 +125,13 @@ def add_route(self, command: Text, adapter: AdapterSpec) -> 'RoutingWrapper':

return self

def get_adapter(self, command: Text) -> BaseAdapter:
def get_adapter(self, command: str) -> BaseAdapter:
"""
Return the adapter for the specified command.
"""
return self.routes.get(command, self.adapter)

async def send_request(self, payload: Dict, **kwargs: Any) -> Dict:
async def send_request(self, payload: dict, **kwargs: Any) -> dict:
command = payload.get('command')

return await self.get_adapter(command).send_request(payload, **kwargs)
Loading

0 comments on commit 0e609ad

Please sign in to comment.