Skip to content

Commit 567d569

Browse files
committed
Fix type hints and pep8 syntax errors
Signed-off-by: Roald Nefs <info@roaldnefs.com>
1 parent 92d90c9 commit 567d569

2 files changed

Lines changed: 42 additions & 29 deletions

File tree

transip/__init__.py

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@
1818
# along with python-transip. If not, see <https://www.gnu.org/licenses/>.
1919
"""Wrapper for the TransIP API."""
2020

21+
from typing import Dict, Optional, Any, Type, Union
22+
2123
import importlib
2224
import requests
23-
import base64
24-
25-
from typing import Dict, Optional, Any, Type
25+
import os
2626

2727
from transip.exceptions import TransIPHTTPError, TransIPParsingError
2828
from transip.utils import generate_message_signature, generate_nonce
@@ -44,7 +44,7 @@ class TransIP:
4444
api_version (str): TransIP API version to use
4545
access_token (str): The TransIP API access token
4646
private_key (str): The content of the private key for accessing the
47-
TransIP API
47+
TransIP API
4848
private_key_file (str): Path to the private key for accessing the
4949
TransIP API
5050
"""
@@ -69,7 +69,7 @@ def __init__(
6969
self.session: requests.Session = requests.Session()
7070

7171
# Set authentication information
72-
self._login: str = login
72+
self._login: Optional[str] = login
7373
self._access_token: Optional[str] = access_token
7474
self._private_key: Optional[str] = private_key
7575
self._private_key_file: Optional[str] = private_key_file
@@ -116,7 +116,6 @@ def _request_access_token(self) -> str:
116116
TransIPParsingError: If the requested access token couldn't be
117117
extracted from the API response.
118118
"""
119-
120119
url: str = self._build_url('/auth')
121120
payload: Dict[str, Any] = {
122121
"login": self._login,
@@ -137,14 +136,22 @@ def _request_access_token(self) -> str:
137136
}
138137

139138
headers: Dict[str, str] = self.headers.copy()
140-
request: requests.Request = requests.Request("POST", url, headers=headers, json=payload)
141-
prepped: requests.PreparedRequest = self.session.prepare_request(request)
139+
request: requests.Request = requests.Request(
140+
"POST", url, headers=headers, json=payload
141+
)
142+
prepped: requests.PreparedRequest = self.session.prepare_request(
143+
request
144+
)
142145

143146
# Get the prepped body for signature generation
144-
body: str = prepped.body
147+
body: Union[bytes, str] = prepped.body or ''
148+
if isinstance(body, bytes):
149+
body = body.decode('ascii')
145150

146151
# Generate a signature if the request body
147-
signature: str = generate_message_signature(body, self._private_key)
152+
signature: str = generate_message_signature(
153+
body, self._private_key # type: ignore
154+
)
148155

149156
# Add 'Signature' header to the prepared request
150157
prepped.headers["Signature"] = signature
@@ -165,13 +172,13 @@ def _read_private_key(self) -> str:
165172
166173
Returns:
167174
str: The private key content
168-
175+
169176
Raises:
170177
RuntimeError: If the private key file doesn't exist
171178
"""
172-
if os.path.exists(self._private_key_file):
179+
if os.path.exists(self._private_key_file): # type: ignore
173180
try:
174-
with open(self._private_key_file) as keyfile:
181+
with open(self._private_key_file) as keyfile: # type: ignore
175182
return keyfile.read()
176183
except IOError as exc:
177184
raise RuntimeError("The private key couldn't be read") from exc
@@ -181,11 +188,12 @@ def _read_private_key(self) -> str:
181188
def _set_auth_info(self) -> None:
182189
"""
183190
Set authentication information based upon the defined attributes.
184-
191+
185192
Raises:
186193
ValueError: If the required attributes are not defined.
187194
"""
188-
if not self._access_token and not self._private_key and not self._private_key_file:
195+
if (not self._access_token and not self._private_key and not
196+
self._private_key_file):
189197
raise ValueError(
190198
"At least one of access_token, private_key and "
191199
"private_key_file should be defined"
@@ -270,7 +278,7 @@ def request(
270278
def _validate_response(self, response: requests.Response) -> Any:
271279
"""
272280
Validate the API response.
273-
281+
274282
Raises:
275283
TransIPHTTPError: When the return code of the request is not 2xx
276284
TransIPParsingError: When the content couldn't be parsed as JSON

transip/utils.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with python-transip. If not, see <https://www.gnu.org/licenses/>.
1919

20+
from typing import Union
21+
2022
import base64
21-
import os
2223
import secrets
2324
import string
2425

@@ -29,45 +30,49 @@
2930
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
3031

3132

32-
def load_rsa_private_key(key: str) -> RSAPrivateKey:
33+
def load_rsa_private_key(key: Union[bytes, str]) -> RSAPrivateKey:
3334
"""
3435
Convert the private key string to RSAPrivateKey object.
35-
36+
3637
Returns:
3738
RSAPrivateKey: The private RSA key.
3839
"""
3940
# Convert the key string to bytes
4041
if isinstance(key, str):
41-
key: bytes = key.encode()
42-
42+
key = key.encode()
43+
4344
return serialization.load_pem_private_key(
4445
key, password=None, backend=default_backend()
4546
)
4647

4748

48-
def generate_message_signature(message: str, private_key: str) -> str:
49+
def generate_message_signature(
50+
message: Union[str, bytes],
51+
private_key: Union[RSAPrivateKey, str]
52+
) -> str:
4953
"""Return the BASE64 encoded SHA514 signature of a message.
50-
54+
5155
Args:
5256
message (str): The message to sign.
5357
private_key (str): The private key content used to sign the message.
54-
58+
5559
Returns:
5660
str: The BASE64 encoded SHA514 signature of a message.
5761
"""
5862
# Convert the message string to bytes
5963
if isinstance(message, str):
60-
message: bytes = message.encode()
64+
message = message.encode()
6165

6266
# Convert the private key content to a RSAPrivateKey object
6367
if isinstance(private_key, str):
64-
private_key: RSAPrivateKey = load_rsa_private_key(private_key)
68+
private_key = load_rsa_private_key(private_key)
6569

6670
# Sign the message using the RSAPrivateKey object
67-
signature: str = private_key.sign(message, PKCS1v15(), SHA512())
71+
signature: bytes = private_key.sign(message, PKCS1v15(), SHA512())
6872

6973
# Return the BASE64 encoded SHA512 signature
70-
return base64.b64encode(signature)
74+
b64_bytes: bytes = base64.b64encode(signature)
75+
return b64_bytes.decode('ascii')
7176

7277

7378
def generate_nonce(length: int) -> str:
@@ -80,5 +85,5 @@ def generate_nonce(length: int) -> str:
8085
Returns:
8186
str: The nonce of specified characters.
8287
"""
83-
alphabet = string.ascii_letters + string.digits
88+
alphabet: str = string.ascii_letters + string.digits
8489
return ''.join(secrets.choice(alphabet) for i in range(length))

0 commit comments

Comments
 (0)