Skip to content

Commit

Permalink
Merge pull request #300 from zowe/Standardize-function-names
Browse files Browse the repository at this point in the history
Standardize function names
  • Loading branch information
zFernand0 authored Jul 1, 2024
2 parents ecf386c + dd86da8 commit 91d87ee
Show file tree
Hide file tree
Showing 22 changed files with 207 additions and 196 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ All notable changes to the Zowe Client Python SDK will be documented in this fil

### Bug Fixes

- *Breaking*: Replaced `datasets` in function names with `data_sets` as a standard. [#83] (https://github.com/zowe/zowe-client-python-sdk/issues/83)
- *Breaking*: Made unnecessary public variables to private [#83] (https://github.com/zowe/zowe-client-python-sdk/issues/83)
- `profile_manager._appname -> profile_manager.__appname`
- `profile_manager._show_warnings -> profile_manager.__show_warnings`
- `... and others ...`
- Fixed `Files.create_data_set` to accept "FBA", "FBM", "VBA", "VBM" as valid recfm [#240](https://github.com/zowe/zowe-client-python-sdk/issues/240)
- Fixed an issue with `Jobs.list_jobs` user correlator parameter [#242](https://github.com/zowe/zowe-client-python-sdk/issues/242)
- Fixed default encoding for I/O operations to be UTF-8 on Windows [#243](https://github.com/zowe/zowe-client-python-sdk/issues/243)
Expand Down
3 changes: 1 addition & 2 deletions src/core/zowe/core_for_zowe_sdk/config_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,12 @@
import commentjson
import requests

from .logger import Log
from .credential_manager import CredentialManager
from .custom_warnings import ProfileNotFoundWarning, ProfileParsingWarning
from .exceptions import ProfileNotFound
from .logger import Log
from .profile_constants import GLOBAL_CONFIG_NAME, TEAM_CONFIG, USER_CONFIG
from .validators import validate_config_json
from .logger import Log

HOME = os.path.expanduser("~")
GLOBAL_CONFIG_LOCATION = os.path.join(HOME, ".zowe")
Expand Down
53 changes: 29 additions & 24 deletions src/core/zowe/core_for_zowe_sdk/profile_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,27 @@ class ProfileManager:
"""

def __init__(self, appname: str = "zowe", show_warnings: bool = True):
self._appname = appname
self._show_warnings = show_warnings
self.__appname = appname
self.__show_warnings = show_warnings

self.project_config = ConfigFile(type=TEAM_CONFIG, name=appname)
self.project_user_config = ConfigFile(type=USER_CONFIG, name=appname)
self.__project_config = ConfigFile(type=TEAM_CONFIG, name=appname)
self.__project_user_config = ConfigFile(type=USER_CONFIG, name=appname)

self.__logger = Log.registerLogger(__name__)

self.global_config = ConfigFile(type=TEAM_CONFIG, name=GLOBAL_CONFIG_NAME)
self.__global_config = ConfigFile(type=TEAM_CONFIG, name=GLOBAL_CONFIG_NAME)
try:
self.global_config.location = GLOBAL_CONFIG_LOCATION
self.__global_config.location = GLOBAL_CONFIG_LOCATION
except Exception:
self.__logger.warning("Could not find Global Config Directory")
warnings.warn(
"Could not find Global Config Directory, please provide one.",
ConfigNotFoundWarning,
)

self.global_user_config = ConfigFile(type=USER_CONFIG, name=GLOBAL_CONFIG_NAME)
self.__global_user_config = ConfigFile(type=USER_CONFIG, name=GLOBAL_CONFIG_NAME)
try:
self.global_user_config.location = GLOBAL_CONFIG_LOCATION
self.__global_user_config.location = GLOBAL_CONFIG_LOCATION
except Exception:
self.__logger.warning("Could not find Global User Config Directory")
warnings.warn(
Expand All @@ -83,40 +83,40 @@ def __init__(self, appname: str = "zowe", show_warnings: bool = True):
@property
def config_appname(self) -> str:
"""Returns the app name"""
return self._appname
return self.__appname

@property
def config_dir(self) -> Optional[str]:
"""Returns the folder path to where the Zowe z/OSMF Team Project Config files are located."""
return self.project_config.location
return self.__project_config.location

@config_dir.setter
def config_dir(self, dirname: str) -> None:
"""
Set directory/folder path to where Zowe z/OSMF Team Project Config files are located
"""
self.project_config.location = dirname
self.project_user_config.location = dirname
self.__project_config.location = dirname
self.__project_user_config.location = dirname

@property
def user_config_dir(self) -> Optional[str]:
"""Returns the folder path to where the Zowe z/OSMF User Project Config files are located."""
return self.project_user_config.location
return self.__project_user_config.location

@user_config_dir.setter
def user_config_dir(self, dirname: str) -> None:
"""Set directory/folder path to where Zowe z/OSMF User Project Config files are located"""
self.project_user_config.location = dirname
self.__project_user_config.location = dirname

@property
def config_filename(self) -> str:
"""Return the filename for Zowe z/OSMF Team Project Config"""
return self.project_config.filename
return self.__project_config.filename

@property
def config_filepath(self) -> Optional[str]:
"""Get the full Zowe z/OSMF Team Project Config filepath"""
return self.project_config.filepath
return self.__project_config.filepath

@staticmethod
def get_env(cfg: ConfigFile, cwd=None) -> dict:
Expand Down Expand Up @@ -262,7 +262,7 @@ def load(
error_msg="Could not find profile as both profile_name and profile_type is not set.",
)

if not self._show_warnings:
if not self.__show_warnings:
warnings.simplefilter("ignore")

profile_props: dict = {}
Expand All @@ -275,7 +275,12 @@ def load(
cfg_schema = None
cfg_schema_dir = None

for cfg_layer in (self.project_user_config, self.project_config, self.global_user_config, self.global_config):
for cfg_layer in (
self.__project_user_config,
self.__project_config,
self.__global_user_config,
self.__global_config,
):
if cfg_layer.profiles is None:
try:
cfg_layer.init_from_file(validate_schema, suppress_config_file_warnings)
Expand All @@ -294,12 +299,12 @@ def load(
cfg_schema = cfg_layer.schema_property
cfg_schema_dir = cfg_layer._location

usrProject = self.project_user_config.profiles or {}
project = self.project_config.profiles or {}
usrProject = self.__project_user_config.profiles or {}
project = self.__project_config.profiles or {}
project_temp = always_merger.merge(deepcopy(project), usrProject)

usrGlobal = self.global_user_config.profiles or {}
global_ = self.global_config.profiles or {}
usrGlobal = self.__global_user_config.profiles or {}
global_ = self.__global_config.profiles or {}
global_temp = always_merger.merge(deepcopy(global_), usrGlobal)

profiles_merged = project_temp
Expand Down Expand Up @@ -359,7 +364,7 @@ def get_highest_priority_layer(self, json_path: str) -> Optional[ConfigFile]:
"""
highest_layer = None
longest_match = ""
layers = [self.project_user_config, self.project_config, self.global_user_config, self.global_config]
layers = [self.__project_user_config, self.__project_config, self.__global_user_config, self.__global_config]

original_name = layers[0].get_profile_name_from_path(json_path)

Expand Down Expand Up @@ -426,7 +431,7 @@ def save(self) -> None:
"""
Save the layers (configuration files) to disk.
"""
layers = [self.project_user_config, self.project_config, self.global_user_config, self.global_config]
layers = [self.__project_user_config, self.__project_config, self.__global_user_config, self.__global_config]

for layer in layers:
layer.save(False)
Expand Down
50 changes: 25 additions & 25 deletions src/core/zowe/core_for_zowe_sdk/request_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def __init__(self, session_arguments, logger_name=__name__):
"""
self.session = requests.Session()
self.session_arguments = session_arguments
self.valid_methods = ["GET", "POST", "PUT", "DELETE"]
self.__valid_methods = ["GET", "POST", "PUT", "DELETE"]
self.__handle_ssl_warnings()
self.__logger = Log.registerLogger(logger_name)

Expand Down Expand Up @@ -71,17 +71,17 @@ def perform_request(self, method, request_arguments, expected_code=[200], stream
normalized_response: json
normalized request response in json (dictionary)
"""
self.method = method
self.request_arguments = request_arguments
self.expected_code = expected_code
self.__method = method
self.__request_arguments = request_arguments
self.__expected_code = expected_code
self.__logger.debug(
f"Request method: {self.method}, Request arguments: {self.request_arguments}, Expected code: {expected_code}"
f"Request method: {self.__method}, Request arguments: {self.__request_arguments}, Expected code: {expected_code}"
)
self.__validate_method()
self.__send_request(stream=stream)
self.__validate_response()
if stream:
return self.response
return self.__response
return self.__normalize_response()

def __validate_method(self):
Expand All @@ -92,16 +92,16 @@ def __validate_method(self):
InvalidRequestMethod
If the input request method is not supported
"""
if self.method not in self.valid_methods:
self.__logger.error(f"Invalid HTTP method input {self.method}")
raise InvalidRequestMethod(self.method)
if self.__method not in self.__valid_methods:
self.__logger.error(f"Invalid HTTP method input {self.__method}")
raise InvalidRequestMethod(self.__method)

def __send_request(self, stream=False):
"""Build a custom session object, prepare it with a custom request and send it."""
session = self.session
request_object = requests.Request(method=self.method, **self.request_arguments)
request_object = requests.Request(method=self.__method, **self.__request_arguments)
prepared = session.prepare_request(request_object)
self.response = session.send(prepared, stream=stream, **self.session_arguments)
self.__response = session.send(prepared, stream=stream, **self.session_arguments)

def __del__(self):
"""Clean up the REST session object once it is no longer needed anymore"""
Expand All @@ -118,21 +118,21 @@ def __validate_response(self):
If the HTTP/HTTPS request fails
"""
# Automatically checks if status code is between 200 and 400
if self.response.ok:
if self.response.status_code not in self.expected_code:
if self.__response.ok:
if self.__response.status_code not in self.__expected_code:
self.__logger.error(
f"The status code from z/OSMF was: {self.expected_code}\nExpected: {self.response.status_code}\nRequest output:{self.response.text}"
f"The status code from z/OSMF was: {self.__expected_code}\nExpected: {self.__response.status_code}\nRequest output:{self.__response.text}"
)
raise UnexpectedStatus(self.expected_code, self.response.status_code, self.response.text)
raise UnexpectedStatus(self.__expected_code, self.__response.status_code, self.__response.text)
else:
output_str = str(self.response.request.url)
output_str += "\n" + str(self.response.request.headers)
output_str += "\n" + str(self.response.request.body)
output_str += "\n" + str(self.response.text)
output_str = str(self.__response.request.url)
output_str += "\n" + str(self.__response.request.headers)
output_str += "\n" + str(self.__response.request.body)
output_str += "\n" + str(self.__response.text)
self.__logger.error(
f"HTTP Request has failed with status code {self.response.status_code}. \n {output_str}"
f"HTTP Request has failed with status code {self.__response.status_code}. \n {output_str}"
)
raise RequestFailed(self.response.status_code, output_str)
raise RequestFailed(self.__response.status_code, output_str)

def __normalize_response(self):
"""Normalize the response object to a JSON format.
Expand All @@ -144,10 +144,10 @@ def __normalize_response(self):
- object when the response is JSON text
- `str` when the response is plain text
"""
contentType = self.response.headers.get("Content-Type")
contentType = self.__response.headers.get("Content-Type")
if contentType == "application/octet-stream":
return self.response.content
return self.__response.content
elif contentType and contentType.startswith("application/json"):
return "" if self.response.text == "" else self.response.json()
return "" if self.__response.text == "" else self.__response.json()
else:
return self.response.text
return self.__response.text
32 changes: 15 additions & 17 deletions src/core/zowe/core_for_zowe_sdk/sdk_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,51 +11,49 @@
"""

import urllib
from .logger import Log

from . import session_constants
from .logger import Log
from .request_handler import RequestHandler
from .session import ISession, Session
from .logger import Log


class SdkApi:
"""
Abstract class used to represent the base SDK API.
"""

def __init__(self, profile, default_url, logger_name = __name__):
self.profile = profile
def __init__(self, profile, default_url, logger_name=__name__):
session = Session(profile)
self.session: ISession = session.load()

self.logger = Log.registerLogger(logger_name)

self.default_service_url = default_url
self.default_headers = {
self._default_service_url = default_url
self._default_headers = {
"Content-Type": "application/json",
"X-CSRF-ZOSMF-HEADER": "",
}

self.request_endpoint = session.host_url + self.default_service_url
self._request_endpoint = session.host_url + self._default_service_url

self.request_arguments = {
"url": self.request_endpoint,
"headers": self.default_headers,
self._request_arguments = {
"url": self._request_endpoint,
"headers": self._default_headers,
}
self.session_arguments = {
self.__session_arguments = {
"verify": self.session.rejectUnauthorized,
"timeout": 30,
}
self.request_handler = RequestHandler(self.session_arguments, logger_name = logger_name)
self.request_handler = RequestHandler(self.__session_arguments, logger_name=logger_name)

if self.session.type == session_constants.AUTH_TYPE_BASIC:
self.request_arguments["auth"] = (self.session.user, self.session.password)
self._request_arguments["auth"] = (self.session.user, self.session.password)
elif self.session.type == session_constants.AUTH_TYPE_BEARER:
self.default_headers["Authorization"] = f"Bearer {self.session.tokenValue}"
self._default_headers["Authorization"] = f"Bearer {self.session.tokenValue}"
elif self.session.type == session_constants.AUTH_TYPE_TOKEN:
self.default_headers["Cookie"] = f"{self.session.tokenType}={self.session.tokenValue}"
self._default_headers["Cookie"] = f"{self.session.tokenType}={self.session.tokenValue}"

def __enter__(self):
return self

Expand All @@ -68,7 +66,7 @@ def _create_custom_request_arguments(self):
This method is required because the way that Python handles
dictionary creation
"""
return self.request_arguments.copy()
return self._request_arguments.copy()

def _encode_uri_component(self, str_to_adjust):
"""Adjust string to be correct in a URL
Expand Down
14 changes: 7 additions & 7 deletions src/core/zowe/core_for_zowe_sdk/zosmf_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def __init__(self, profile_name):
profile_name
The name of the Zowe z/OSMF profile
"""
self.profile_name = profile_name
self.__profile_name = profile_name
self.__logger = Log.registerLogger(__name__)

@property
Expand All @@ -69,7 +69,7 @@ def load(self):
zosmf_connection
z/OSMF connection object
"""
profile_file = os.path.join(self.profiles_dir, "{}.yaml".format(self.profile_name))
profile_file = os.path.join(self.profiles_dir, "{}.yaml".format(self.__profile_name))

with open(profile_file, "r") as fileobj:
profile_yaml = yaml.safe_load(fileobj)
Expand All @@ -93,7 +93,7 @@ def load(self):

def __get_secure_value(self, name):
service_name = constants["ZoweCredentialKey"]
account_name = "zosmf_{}_{}".format(self.profile_name, name)
account_name = "zosmf_{}_{}".format(self.__profile_name, name)

secret_value = keyring.get_password(service_name, account_name)

Expand All @@ -108,14 +108,14 @@ def __get_secure_value(self, name):
def __load_secure_credentials(self):
"""Load secure credentials for a z/OSMF profile."""
if not HAS_KEYRING:
self.__logger.error(f"{self.profile_name} keyring module not installed")
raise SecureProfileLoadFailed(self.profile_name, "Keyring module not installed")
self.__logger.error(f"{self.__profile_name} keyring module not installed")
raise SecureProfileLoadFailed(self.__profile_name, "Keyring module not installed")

try:
zosmf_user = self.__get_secure_value("user")
zosmf_password = self.__get_secure_value("password")
except Exception as e:
self.__logger.error(f"Failed to load secure profile '{self.profile_name}' because '{e}'")
raise SecureProfileLoadFailed(self.profile_name, e)
self.__logger.error(f"Failed to load secure profile '{self.__profile_name}' because '{e}'")
raise SecureProfileLoadFailed(self.__profile_name, e)
else:
return (zosmf_user, zosmf_password)
Loading

0 comments on commit 91d87ee

Please sign in to comment.