Skip to content

Commit

Permalink
REFACTOR: Generic modules to avoid bad pratices
Browse files Browse the repository at this point in the history
Note: use 'secrets' module instead of random values
created through 'random' module.
  • Loading branch information
SMoraisAnsys committed May 5, 2024
1 parent 9936f70 commit c75f29f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 25 deletions.
4 changes: 3 additions & 1 deletion pyaedt/generic/clr_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import sys
import warnings

from pyaedt.aedt_logger import pyaedt_logger as logger

modules = [tup[1] for tup in pkgutil.iter_modules()]
pyaedt_path = os.path.dirname(os.path.dirname(__file__))
cpython = "IronPython" not in sys.version and ".NETFramework" not in sys.version
Expand Down Expand Up @@ -49,7 +51,7 @@
is_clr = True

except Exception:
pass
logger.error("An error occurred while loading clr.")


try: # work around a number formatting bug in the EDB API for non-English locales
Expand Down
4 changes: 3 additions & 1 deletion pyaedt/generic/filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import shutil
import string

from pyaedt.aedt_logger import pyaedt_logger as logger


def search_files(dirname, pattern="*"):
"""Search for files inside a directory given a specific pattern.
Expand Down Expand Up @@ -69,7 +71,7 @@ def remove(self):
# TODO check why on Anaconda 3.7 get errors with os.path.exists
shutil.rmtree(self._scratch_path, ignore_errors=True)
except Exception:
pass
logger.error("An error occurred while removing {}".format(self._scratch_path))

def copyfile(self, src_file, dst_filename=None):
"""
Expand Down
37 changes: 14 additions & 23 deletions pyaedt/generic/general_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
import json
import math
import os
import random
import re
import secrets
import string
import sys
import tempfile
Expand All @@ -29,20 +29,11 @@
is_ironpython = "IronPython" in sys.version or ".NETFramework" in sys.version
is_linux = os.name == "posix"
is_windows = not is_linux
_pythonver = sys.version_info[0]
_python_current_release = sys.version_info[1]
inside_desktop = True if is_ironpython and "4.0.30319.42000" in sys.version else False

if not is_ironpython:
import psutil

try:
import xml.etree.cElementTree as ET

ET.VERSION
except ImportError:
ET = None


class GrpcApiError(Exception):
""" """
Expand Down Expand Up @@ -137,7 +128,6 @@ def _exception(ex_info, func, args, kwargs, message="Type Error"):
if message_to_print:
_write_mes("Last Electronics Desktop Message - " + message_to_print)

args_name = []
try:
args_dict = _get_args_dicts(func, args, kwargs)
first_time_log = True
Expand All @@ -149,12 +139,12 @@ def _exception(ex_info, func, args, kwargs, message="Type Error"):
first_time_log = False
_write_mes(" {} = {} ".format(el, args_dict[el]))
except Exception:
pass
args = [func.__name__] + [i for i in args_name if i not in ["self"]]
pyaedt_logger.error("An error occurred while parsing and logging an error with method {}.")

if not func.__name__.startswith("_"):
_write_mes(
"Check Online documentation on: https://aedt.docs.pyansys.com/version/stable/search.html?q={}".format(
"+".join(args)
func.__name__
)
)
_write_mes(header)
Expand Down Expand Up @@ -705,8 +695,8 @@ def generate_unique_name(rootname, suffix="", n=6):
Newly generated name.
"""
char_set = string.ascii_uppercase + string.digits
uName = "".join(random.choice(char_set) for _ in range(n))
alphabet = string.ascii_uppercase + string.digits
uName = "".join(secrets.choice(alphabet) for _ in range(n))
unique_name = rootname + "_" + uName
if suffix:
unique_name += "_" + suffix
Expand Down Expand Up @@ -799,7 +789,7 @@ def _retry_ntimes(n, function, *args, **kwargs):
if function.__name__ == "InvokeAedtObjMethod":
func_name = args[1]
except Exception:
pass
pyaedt_logger.debug("An error occurred while accessing the arguments of a function " "called multiple times.")
retry = 0
ret_val = None
inclusion_list = [
Expand Down Expand Up @@ -1409,7 +1399,7 @@ def active_sessions(version=None, student_version=False, non_graphical=False):
return_dict[p.pid] = i.laddr.port
break
except Exception:
pass
pyaedt_logger.error("An error occurred while retrieving information for the active AEDT sessions")
return return_dict


Expand Down Expand Up @@ -1910,8 +1900,9 @@ def _uname(name=None):
str
"""
char_set = string.ascii_uppercase + string.digits
unique_name = "".join(random.sample(char_set, 6))
alphabet = string.ascii_uppercase + string.digits
generator = secrets.SystemRandom()
unique_name = "".join(secrets.SystemRandom.sample(generator, alphabet, 6))
if name:
return name + unique_name
else:
Expand Down Expand Up @@ -1995,7 +1986,7 @@ def _check_installed_version(install_path, long_version):
if install_version == long_version:
return True
except Exception:
pass
pyaedt_logger.debug("An error occurred while parsing installation version")
return False


Expand All @@ -2015,9 +2006,9 @@ def install_with_pip(package_name, package_path=None, upgrade=False, uninstall=F
Whether to install the package or uninstall the package.
"""
if is_linux and is_ironpython:
import subprocessdotnet as subprocess
import subprocessdotnet as subprocess # nosec B404
else:
import subprocess
import subprocess # nosec B404
executable = '"{}"'.format(sys.executable) if is_windows else sys.executable

commands = []
Expand Down

0 comments on commit c75f29f

Please sign in to comment.