Skip to content

Commit 66b711f

Browse files
authored
Merge pull request #322 from zowe/Response-Type-for-REST-APT
Update REST API response type
2 parents 9c42f3b + f87c516 commit 66b711f

File tree

37 files changed

+943
-146
lines changed

37 files changed

+943
-146
lines changed

.github/workflows/sdk-build.yml

+3-3
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,15 @@ jobs:
2929
python -m pip install --upgrade pip
3030
pip install -r requirements.txt
3131
- name: Lint with pydocstyle
32-
run: pydocstyle --match-dir='^(?!build$).*' --match='^(?!(__init__\.py|setup\.py$)).*\.py$' src
32+
run: pydocstyle --match-dir='^(?!(build|response)$).*' --match='^(?!(__init__\.py|setup\.py$)).*\.py$' src
3333
- name: Lint with pydoclint
34-
run: pydoclint --exclude='.*/build/.*' src
34+
run: pydoclint --exclude='.*/(build|response)/.*' src
3535
- name: Lint with pylint
3636
run: |
3737
# check for Python errors
3838
pylint src --errors-only --disable=E0401,E0611 --ignore=build
3939
# check for lint
40-
pylint ./src --disable=all --enable=C0103,C0301 --ignore=build --max-line-length=127
40+
pylint ./src --disable=all --enable=C0103,C0301 --ignore=build,response --max-line-length=127
4141
- name: Check license headers
4242
run: python scripts/license_header.py src
4343
- name: Test with pytest

.vscode/settings.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
"./src/zos_console",
1818
"./src/zos_files",
1919
"./src/zos_jobs",
20-
"./src/zosmf"
20+
"./src/zosmf",
21+
"./src/zos_tso"
2122
],
2223
"python.linting.enabled": true,
2324
"python.linting.pylintEnabled": true,

CHANGELOG.md

+9
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,15 @@
22

33
All notable changes to the Zowe Client Python SDK will be documented in this file.
44

5+
## Recent Changes
6+
7+
### Enhancements
8+
9+
- *Breaking*: Update method return types to use custom classes for REST API responses [#89] (https://github.com/zowe/zowe-client-python-sdk/issues/89)
10+
11+
### Bug Fixes
12+
13+
514
## `1.0.0-dev19`
615

716
### Enhancements

scripts/license_header.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def main():
4040
if "build" in root.split(os.path.sep):
4141
continue
4242
for file in files:
43-
if file.endswith(".py"):
43+
if file.endswith(".py") and file is not "_version.py":
4444
file_path = os.path.join(root, file)
4545
if not check_and_add_license_header(file_path, write_header):
4646
print(f"License header missing in: {file_path}")

src/_version.py

+11
Original file line numberDiff line numberDiff line change
@@ -1 +1,12 @@
1+
"""Zowe Python Client SDK.
2+
3+
This program and the accompanying materials are made available under the terms of the
4+
Eclipse Public License v2.0 which accompanies this distribution, and is available at
5+
6+
https://www.eclipse.org/legal/epl-v20.html
7+
8+
SPDX-License-Identifier: EPL-2.0
9+
10+
Copyright Contributors to the Zowe Project.
11+
"""
112
__version__ = "1.0.0-dev19"

src/core/zowe/core_for_zowe_sdk/request_handler.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ def __handle_ssl_warnings(self):
4444
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
4545

4646
def perform_request(
47-
self, method: str, request_arguments: dict, expected_code: dict = [200], stream: bool = False
48-
) -> dict:
47+
self, method: str, request_arguments: dict, expected_code: list = [200], stream: bool = False
48+
) -> Union[str, bytes, dict, None]:
4949
"""Execute an HTTP/HTTPS requests from given arguments and return validated response (JSON).
5050
5151
Parameters
@@ -54,14 +54,14 @@ def perform_request(
5454
The request method that should be used
5555
request_arguments: dict
5656
The dictionary containing the required arguments for the execution of the request
57-
expected_code: dict
57+
expected_code: list
5858
The list containing the acceptable response codes (default is [200])
5959
stream: bool
6060
The boolean value whether the request is stream
6161
6262
Returns
6363
-------
64-
dict
64+
Union[str, bytes, dict, None]
6565
normalized request response in json (dictionary)
6666
"""
6767
self.__method = method
@@ -136,13 +136,13 @@ def __validate_response(self):
136136
)
137137
raise RequestFailed(self.__response.status_code, output_str)
138138

139-
def __normalize_response(self) -> Union[str, bytes, dict]:
139+
def __normalize_response(self) -> Union[str, bytes, dict, None]:
140140
"""
141141
Normalize the response object to a JSON format.
142142
143143
Returns
144144
-------
145-
Union[str, bytes, dict]
145+
Union[str, bytes, dict, None]
146146
Response object at the format based on Content-Type header:
147147
- `bytes` when the response is binary data
148148
- `str` when the response is plain text
@@ -152,6 +152,6 @@ def __normalize_response(self) -> Union[str, bytes, dict]:
152152
if content_type == "application/octet-stream":
153153
return self.__response.content
154154
elif content_type and content_type.startswith("application/json"):
155-
return "" if self.__response.text == "" else self.__response.json()
155+
return None if self.__response.text == "" else self.__response.json()
156156
else:
157157
return self.__response.text

src/zos_console/zowe/zos_console_for_zowe_sdk/console.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
from zowe.core_for_zowe_sdk import SdkApi
1616

17+
from .response import ConsoleResponse, IssueCommandResponse
18+
1719

1820
class Console(SdkApi):
1921
"""
@@ -28,7 +30,7 @@ class Console(SdkApi):
2830
def __init__(self, connection: dict):
2931
super().__init__(connection, "/zosmf/restconsoles/consoles/defcn", logger_name=__name__)
3032

31-
def issue_command(self, command: str, console: Optional[str] = None) -> dict:
33+
def issue_command(self, command: str, console: Optional[str] = None) -> IssueCommandResponse:
3234
"""Issues a command on z/OS Console.
3335
3436
Parameters
@@ -40,17 +42,17 @@ def issue_command(self, command: str, console: Optional[str] = None) -> dict:
4042
4143
Returns
4244
-------
43-
dict
45+
IssueCommandResponse
4446
A JSON containing the response from the console command
4547
"""
4648
custom_args = self._create_custom_request_arguments()
4749
custom_args["url"] = self._request_endpoint.replace("defcn", console or "defcn")
4850
request_body = {"cmd": command}
4951
custom_args["json"] = request_body
5052
response_json = self.request_handler.perform_request("PUT", custom_args)
51-
return response_json
53+
return IssueCommandResponse(response_json)
5254

53-
def get_response(self, response_key: str, console: Optional[str] = None) -> dict:
55+
def get_response(self, response_key: str, console: Optional[str] = None) -> ConsoleResponse:
5456
"""
5557
Collect outstanding synchronous z/OS Console response messages.
5658
@@ -63,11 +65,11 @@ def get_response(self, response_key: str, console: Optional[str] = None) -> dict
6365
6466
Returns
6567
-------
66-
dict
68+
ConsoleResponse
6769
A JSON containing the response to the command
6870
"""
6971
custom_args = self._create_custom_request_arguments()
7072
request_url = "{}/solmsgs/{}".format(console or "defcn", response_key)
7173
custom_args["url"] = self._request_endpoint.replace("defcn", request_url)
7274
response_json = self.request_handler.perform_request("GET", custom_args)
73-
return response_json
75+
return ConsoleResponse(response_json)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
"""Zowe Python Client SDK.
2+
3+
This program and the accompanying materials are made available under the terms of the
4+
Eclipse Public License v2.0 which accompanies this distribution, and is available at
5+
6+
https://www.eclipse.org/legal/epl-v20.html
7+
8+
SPDX-License-Identifier: EPL-2.0
9+
10+
Copyright Contributors to the Zowe Project.
11+
"""
12+
13+
from .console import ConsoleResponse, IssueCommandResponse
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""Zowe Python Client SDK.
2+
3+
This program and the accompanying materials are made available under the terms of the
4+
Eclipse Public License v2.0 which accompanies this distribution, and is available at
5+
6+
https://www.eclipse.org/legal/epl-v20.html
7+
8+
SPDX-License-Identifier: EPL-2.0
9+
10+
Copyright Contributors to the Zowe Project.
11+
"""
12+
13+
from dataclasses import dataclass
14+
from typing import Any, Optional
15+
16+
17+
@dataclass
18+
class IssueCommandResponse:
19+
cmd_response_key: Optional[str] = None
20+
cmd_response_url: Optional[str] = None
21+
cmd_response_uri: Optional[str] = None
22+
cmd_response: Optional[str] = None
23+
24+
def __init__(self, response: dict) -> None:
25+
for k, value in response.items():
26+
key = k.replace("-", "_")
27+
super().__setattr__(key, value)
28+
29+
def __getitem__(self, key: str) -> str:
30+
return self.__dict__[key.replace("-", "_")]
31+
32+
def __setitem__(self, key: str, value: str) -> None:
33+
self.__dict__[key.replace("-", "_")] = value
34+
35+
36+
@dataclass
37+
class ConsoleResponse:
38+
cmd_response: Optional[str] = None
39+
sol_key_detected: Optional[bool] = None
40+
41+
def __init__(self, response: dict) -> None:
42+
for k, value in response.items():
43+
key = k.replace("-", "_")
44+
super().__setattr__(key, value)
45+
46+
def __getitem__(self, key: str) -> Any:
47+
return self.__dict__[key.replace("-", "_")]
48+
49+
def __setitem__(self, key: str, value: Any) -> None:
50+
self.__dict__[key.replace("-", "_")] = value

src/zos_files/zowe/zos_files_for_zowe_sdk/datasets.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from zowe.core_for_zowe_sdk import SdkApi
1818
from zowe.core_for_zowe_sdk.exceptions import FileNotFound
1919
from zowe.zos_files_for_zowe_sdk.constants import FileType, zos_file_constants
20+
from zowe.zos_files_for_zowe_sdk.response import DatasetListResponse, MemberListResponse
2021

2122
_ZOWE_FILES_DEFAULT_ENCODING = zos_file_constants["ZoweFilesDefaultEncoding"]
2223

@@ -306,7 +307,7 @@ def __init__(self, connection: dict):
306307
super().__init__(connection, "/zosmf/restfiles/", logger_name=__name__)
307308
self._default_headers["Accept-Encoding"] = "gzip"
308309

309-
def list(self, name_pattern: str, return_attributes: bool = False) -> List[Dict]:
310+
def list(self, name_pattern: str, return_attributes: bool = False) -> DatasetListResponse:
310311
"""
311312
Retrieve a list of datasets based on a given pattern.
312313
@@ -319,7 +320,7 @@ def list(self, name_pattern: str, return_attributes: bool = False) -> List[Dict]
319320
320321
Returns
321322
-------
322-
List[Dict]
323+
DatasetListResponse
323324
A JSON with a list of dataset names (and attributes if specified) matching the given pattern.
324325
"""
325326
custom_args = self._create_custom_request_arguments()
@@ -330,7 +331,7 @@ def list(self, name_pattern: str, return_attributes: bool = False) -> List[Dict]
330331
custom_args["headers"]["X-IBM-Attributes"] = "base"
331332

332333
response_json = self.request_handler.perform_request("GET", custom_args)
333-
return response_json
334+
return DatasetListResponse(response_json, return_attributes)
334335

335336
def list_members(
336337
self,
@@ -339,7 +340,7 @@ def list_members(
339340
member_start: Optional[str] = None,
340341
limit: int = 1000,
341342
attributes: str = "member",
342-
) -> dict:
343+
) -> MemberListResponse:
343344
"""
344345
Retrieve the list of members on a given PDS/PDSE.
345346
@@ -358,7 +359,7 @@ def list_members(
358359
359360
Returns
360361
-------
361-
dict
362+
MemberListResponse
362363
A JSON with a list of members from a given PDS/PDSE
363364
"""
364365
custom_args = self._create_custom_request_arguments()
@@ -372,7 +373,7 @@ def list_members(
372373
custom_args["headers"]["X-IBM-Max-Items"] = "{}".format(limit)
373374
custom_args["headers"]["X-IBM-Attributes"] = attributes
374375
response_json = self.request_handler.perform_request("GET", custom_args)
375-
return response_json["items"] # type: ignore
376+
return MemberListResponse(response_json, (attributes == "base"))
376377

377378
def copy_data_set_or_member(
378379
self,

src/zos_files/zowe/zos_files_for_zowe_sdk/file_system.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
from zowe.core_for_zowe_sdk import SdkApi
1616
from zowe.zos_files_for_zowe_sdk import constants, exceptions
1717

18+
from .response import FileSystemListResponse
19+
1820
_ZOWE_FILES_DEFAULT_ENCODING = constants.zos_file_constants["ZoweFilesDefaultEncoding"]
1921

2022

@@ -150,7 +152,9 @@ def unmount(self, file_system_name: str, options: dict = {}, encoding: str = _ZO
150152
response_json = self.request_handler.perform_request("PUT", custom_args, expected_code=[204])
151153
return response_json
152154

153-
def list(self, file_path_name: Optional[str] = None, file_system_name: Optional[str] = None) -> dict:
155+
def list(
156+
self, file_path_name: Optional[str] = None, file_system_name: Optional[str] = None
157+
) -> FileSystemListResponse:
154158
"""
155159
List all mounted filesystems.
156160
@@ -166,12 +170,12 @@ def list(self, file_path_name: Optional[str] = None, file_system_name: Optional[
166170
167171
Returns
168172
-------
169-
dict
173+
FileSystemListResponse
170174
A JSON containing the result of the operation
171175
"""
172176
custom_args = self._create_custom_request_arguments()
173177

174178
custom_args["params"] = {"path": file_path_name, "fsname": file_system_name}
175179
custom_args["url"] = "{}mfs".format(self._request_endpoint)
176180
response_json = self.request_handler.perform_request("GET", custom_args, expected_code=[200])
177-
return response_json
181+
return FileSystemListResponse(response_json)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
"""Zowe Python Client SDK.
2+
3+
This program and the accompanying materials are made available under the terms of the
4+
Eclipse Public License v2.0 which accompanies this distribution, and is available at
5+
6+
https://www.eclipse.org/legal/epl-v20.html
7+
8+
SPDX-License-Identifier: EPL-2.0
9+
10+
Copyright Contributors to the Zowe Project.
11+
"""
12+
from .datasets import DatasetListResponse, MemberListResponse
13+
from .file_system import FileSystemListResponse
14+
from .uss import USSListResponse

0 commit comments

Comments
 (0)