diff options
author | Diogo Sousa <montezdesousa@gmail.com> | 2024-04-29 17:21:55 +0100 |
---|---|---|
committer | Diogo Sousa <montezdesousa@gmail.com> | 2024-04-29 17:21:55 +0100 |
commit | fed6c4dea12ed9f70a1ebf2376dfcc52d81eea37 (patch) | |
tree | 410476f15c831c9754832f13c656743e0cc41695 | |
parent | 7bb9d4e34d04f0881a3e6e2ea3f9765ebf68ca6f (diff) |
rename session refs
9 files changed, 209 insertions, 213 deletions
diff --git a/openbb_terminal/openbb_terminal/config/setup.py b/openbb_terminal/openbb_terminal/config/setup.py index c6547a62d59..7a585840d47 100644 --- a/openbb_terminal/openbb_terminal/config/setup.py +++ b/openbb_terminal/openbb_terminal/config/setup.py @@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, List, Optional, TypeVar import i18n from openbb_terminal.config.constants import I18N_FILE +from openbb_terminal.session import Session if TYPE_CHECKING: from openbb_charting.core.openbb_figure import OpenBBFigure @@ -20,6 +21,7 @@ current_figure: Optional[OpenBBFigureT] = None # type: ignore new_axis: bool = True legends: List = [] last_legend = "" +session = Session() # pylint: disable=global-statement @@ -79,6 +81,5 @@ def setup_i18n(i18n_path: Path = I18N_FILE, lang: str = "en"): def setup_config_terminal(): """Setup pre-launch configurations for the terminal.""" # pylint: disable=import-outside-toplevel - from openbb_terminal.session import Session - setup_i18n(lang=Session().settings.USE_LANGUAGE) + setup_i18n(lang=session.settings.USE_LANGUAGE) diff --git a/openbb_terminal/openbb_terminal/controllers/base_controller.py b/openbb_terminal/openbb_terminal/controllers/base_controller.py index 21759214b29..945ba9f7292 100644 --- a/openbb_terminal/openbb_terminal/controllers/base_controller.py +++ b/openbb_terminal/openbb_terminal/controllers/base_controller.py @@ -32,6 +32,7 @@ from openbb_terminal.session import Session # pylint: disable=R0912 controllers: Dict[str, Any] = {} +session = Session() # TODO: We should try to avoid these global variables @@ -133,7 +134,7 @@ class BaseController(metaclass=ABCMeta): def load_class(self, class_ins, *args, **kwargs): """Check for an existing instance of the controller before creating a new one.""" - settings = Session().settings + settings = session.settings self.save_class() arguments = len(args) + len(kwargs) # Due to the 'arguments == 1' condition, we actually NEVER load a class @@ -268,7 +269,7 @@ class BaseController(metaclass=ABCMeta): def save_class(self) -> None: """Save the current instance of the class to be loaded later.""" - if Session().settings.REMEMBER_CONTEXTS: + if session.settings.REMEMBER_CONTEXTS: controllers[self.PATH] = self def custom_reset(self) -> List[str]: @@ -322,7 +323,7 @@ class BaseController(metaclass=ABCMeta): actions = self.parse_input(an_input) if an_input and an_input != "reset": - Session().console.print() + session.console.print() # Empty command if len(actions) == 0: @@ -375,7 +376,7 @@ class BaseController(metaclass=ABCMeta): not self.queue or (self.queue and self.queue[0] not in ("quit", "help")) ) ): - Session().console.print() + session.console.print() return self.queue @@ -386,7 +387,7 @@ class BaseController(metaclass=ABCMeta): def call_home(self, _) -> None: """Process home command.""" self.save_class() - if self.PATH.count("/") == 1 and Session().settings.ENABLE_EXIT_AUTO_HELP: + if self.PATH.count("/") == 1 and session.settings.ENABLE_EXIT_AUTO_HELP: self.print_help() for _ in range(self.PATH.count("/") - 1): self.queue.insert(0, "quit") @@ -407,9 +408,9 @@ class BaseController(metaclass=ABCMeta): for _ in range(self.PATH.count("/")): self.queue.insert(0, "quit") - if not Session().is_local(): + if not session.is_local(): remove_file( - Path(Session().user.preferences.export_directory, "routines", "hub") + Path(session.user.preferences.export_directory, "routines", "hub") ) def call_reset(self, _) -> None: @@ -503,7 +504,7 @@ class BaseController(metaclass=ABCMeta): if ns_parser: if not ns_parser.name: - Session().console.print( + session.console.print( "[red]Set a routine title by using the '-n' flag. E.g. 'record -n Morning routine'[/red]" ) return @@ -514,7 +515,7 @@ class BaseController(metaclass=ABCMeta): else ns_parser.tag1 ) if tag1 and tag1 not in SCRIPT_TAGS: - Session().console.print( + session.console.print( f"[red]The parameter 'tag1' needs to be one of the following {', '.join(SCRIPT_TAGS)}[/red]" ) return @@ -525,7 +526,7 @@ class BaseController(metaclass=ABCMeta): else ns_parser.tag2 ) if tag2 and tag2 not in SCRIPT_TAGS: - Session().console.print( + session.console.print( f"[red]The parameter 'tag2' needs to be one of the following {', '.join(SCRIPT_TAGS)}[/red]" ) return @@ -536,19 +537,19 @@ class BaseController(metaclass=ABCMeta): else ns_parser.tag3 ) if tag3 and tag3 not in SCRIPT_TAGS: - Session().console.print( + session.console.print( f"[red]The parameter 'tag3' needs to be one of the following {', '.join(SCRIPT_TAGS)}[/red]" ) return - if Session().is_local() and not ns_parser.local: - Session().console.print( + if session.is_local() and not ns_parser.local: + session.console.print( "[red]Recording session to the OpenBB Hub is not supported in guest mode.[/red]" ) - Session().console.print( + session.console.print( "\n[yellow]Sign to OpenBB Hub to register: http://openbb.co[/yellow]" ) - Session().console.print( + session.console.print( "\n[yellow]Otherwise set the flag '-l' to save the file locally.[/yellow]" ) return @@ -557,7 +558,7 @@ class BaseController(metaclass=ABCMeta): title = " ".join(ns_parser.name) if ns_parser.name else "" pattern = re.compile(r"^[a-zA-Z0-9\s]+$") if not pattern.match(title): - Session().console.print( + session.console.print( f"[red]Title '{title}' has invalid format. Please use only digits, characters and whitespaces.[/]" ) return @@ -583,10 +584,10 @@ class BaseController(metaclass=ABCMeta): SESSION_RECORDED_PUBLIC = ns_parser.public - Session().console.print( + session.console.print( f"[green]The routine '{title}' is successfully being recorded.[/green]" ) - Session().console.print( + session.console.print( "\n[yellow]Remember to run 'stop' command when you are done!\n[/yellow]" ) @@ -596,15 +597,15 @@ class BaseController(metaclass=ABCMeta): global SESSION_RECORDED # noqa: PLW0603 if not RECORD_SESSION: - Session().console.print( + session.console.print( "[red]There is no session being recorded. Start one using the command 'record'[/red]\n" ) elif len(SESSION_RECORDED) < 5: - Session().console.print( + session.console.print( "[red]Run at least 4 commands before stopping recording a session.[/red]\n" ) else: - current_user = Session().user + current_user = session.user # Check if the user just wants to store routine locally # This works regardless of whether they are logged in or not @@ -621,14 +622,14 @@ class BaseController(metaclass=ABCMeta): # If file already exists, add a timestamp to the name if os.path.isfile(routine_file): - i = Session().console.input( + i = session.console.input( "A local routine with the same name already exists, " "do you want to override it? (y/n): " ) - Session().console.print("") + session.console.print("") while i.lower() not in ["y", "yes", "n", "no"]: - i = Session().console.input("Select 'y' or 'n' to proceed: ") - Session().console.print("") + i = session.console.input("Select 'y' or 'n' to proceed: ") + session.console.print("") if i.lower() in ["n", "no"]: new_name = ( @@ -640,7 +641,7 @@ class BaseController(metaclass=ABCMeta): "routines", new_name, ) - Session().console.print( + session.console.print( f"[yellow]The routine name has been updated to '{new_name}'[/yellow]\n" ) @@ -651,7 +652,7 @@ class BaseController(metaclass=ABCMeta): lines = ["# OpenBB Platform CLI - Routine", "\n"] username = getattr( - Session().user.profile.hub_session, "username", "local" + session.user.profile.hub_session, "username", "local" ) lines += [f"# Author: {username}", "\n\n"] if username else ["\n"] @@ -667,13 +668,13 @@ class BaseController(metaclass=ABCMeta): # Writing data to a file file1.writelines(lines) - Session().console.print( + session.console.print( f"[green]Your routine has been recorded and saved here: {routine_file}[/green]\n" ) # If user doesn't specify they want to store routine locally # Confirm that the user is logged in - elif not Session().is_local(): + elif not session.is_local(): routine = "\n".join(SESSION_RECORDED[:-1]) hub_session = current_user.profile.hub_session @@ -693,16 +694,16 @@ class BaseController(metaclass=ABCMeta): } response = upload_routine(**kwargs) # type: ignore if response is not None and response.status_code == 409: - i = Session().console.input( + i = session.console.input( "A routine with the same name already exists, " "do you want to replace it? (y/n): " ) - Session().console.print("") + session.console.print("") if i.lower() in ["y", "yes"]: kwargs["override"] = True # type: ignore response = upload_routine(**kwargs) # type: ignore else: - Session().console.print("[info]Aborted.[/info]") + session.console.print("[info]Aborted.[/info]") # Clear session to be recorded again RECORD_SESSION = False @@ -719,14 +720,14 @@ class BaseController(metaclass=ABCMeta): ns_parser = self.parse_simple_args(parser, other_args) if ns_parser: - current_user = Session().user - local_user = Session().is_local() + current_user = session.user + local_user = session.is_local() if not local_user: hub_session = current_user.profile.hub_session - Session().console.print( + session.console.print( f"[info]email:[/info] {hub_session.email if hub_session else 'N/A'}" ) - Session().console.print( + session.console.print( f"[info]uuid:[/info] {hub_session.user_uuid if hub_session else 'N/A'}" ) else: @@ -752,23 +753,23 @@ class BaseController(metaclass=ABCMeta): "-h", "--help", action="store_true", help="show this help message" ) - if Session().settings.USE_CLEAR_AFTER_CMD: + if session.settings.USE_CLEAR_AFTER_CMD: system_clear() try: (ns_parser, l_unknown_args) = parser.parse_known_args(other_args) except SystemExit: # In case the command has required argument that isn't specified - Session().console.print("\n") + session.console.print("\n") return None if ns_parser.help: txt_help = parser.format_help() - Session().console.print(f"[help]{txt_help}[/help]") + session.console.print(f"[help]{txt_help}[/help]") return None if l_unknown_args: - Session().console.print( + session.console.print( f"The following args couldn't be interpreted: {l_unknown_args}\n" ) @@ -871,7 +872,7 @@ class BaseController(metaclass=ABCMeta): help="Number of entries to show in data.", type=check_positive, ) - if Session().settings.USE_CLEAR_AFTER_CMD: + if session.settings.USE_CLEAR_AFTER_CMD: system_clear() if "--help" in other_args or "-h" in other_args: @@ -881,7 +882,7 @@ class BaseController(metaclass=ABCMeta): f"For more information and examples, use 'about {parser.prog}' " f"to access the related guide.\n" ) - Session().console.print(f"[help]{txt_help}[/help]") + session.console.print(f"[help]{txt_help}[/help]") return None try: @@ -911,14 +912,14 @@ class BaseController(metaclass=ABCMeta): setup.set_last_legend(" ".join(ns_parser.hold_legend_str)) if l_unknown_args: - Session().console.print( + session.console.print( f"The following args couldn't be interpreted: {l_unknown_args}" ) return ns_parser def menu(self, custom_path_menu_above: str = ""): """Enter controller menu.""" - settings = Session().settings + settings = session.settings an_input = "HELP_ME" while True: @@ -949,7 +950,7 @@ class BaseController(metaclass=ABCMeta): and an_input != "help" and an_input.split(" ")[0] in self.controller_choices ): - Session().console.print( + session.console.print( f"{get_flair_and_username()} {self.PATH} $ {an_input}" ) @@ -960,7 +961,7 @@ class BaseController(metaclass=ABCMeta): self.print_help() try: - prompt_session = Session().prompt_session + prompt_session = session.prompt_session if prompt_session and settings.USE_PROMPT_TOOLKIT: # Check if toolbar hint was enabled if settings.TOOLBAR_HINT: @@ -1003,7 +1004,7 @@ class BaseController(metaclass=ABCMeta): self.queue = self.switch(an_input) except SystemExit: - Session().console.print( + session.console.print( f"[red]The command '{an_input}' doesn't exist on the {self.PATH} menu.[/red]\n", ) similar_cmd = difflib.get_close_matches( @@ -1020,14 +1021,14 @@ class BaseController(metaclass=ABCMeta): if candidate_input == an_input: an_input = "" self.queue = [] - Session().console.print("\n") + session.console.print("\n") continue an_input = candidate_input else: an_input = similar_cmd[0] - Session().console.print( + session.console.print( f"[green]Replacing by '{an_input}'.[/green]\n" ) self.queue.insert(0, an_input) diff --git a/openbb_terminal/openbb_terminal/controllers/base_platform_controller.py b/openbb_terminal/openbb_terminal/controllers/base_platform_controller.py index d75edbc447a..ea4da7b66e4 100644 --- a/openbb_terminal/openbb_terminal/controllers/base_platform_controller.py +++ b/openbb_terminal/openbb_terminal/controllers/base_platform_controller.py @@ -19,6 +19,8 @@ from openbb_terminal.controllers.base_controller import BaseController from openbb_terminal.controllers.utils import export_data, print_rich_table from openbb_terminal.session import Session +session = Session() + class DummyTranslation: """Dummy Translation for testing.""" @@ -69,7 +71,7 @@ class PlatformController(BaseController): self._generate_commands() self._generate_sub_controllers() - if Session().prompt_session and Session().settings.USE_PROMPT_TOOLKIT: + if session.prompt_session and session.settings.USE_PROMPT_TOOLKIT: choices: dict = self.choices_default self.completer = NestedCompleter.from_nested_dict(choices) @@ -178,7 +180,7 @@ class PlatformController(BaseController): print_rich_table(df, show_index=True) elif obbject: - Session().console.print(obbject) + session.console.print(obbject) if hasattr(ns_parser, "export") and ns_parser.export: sheet_name = getattr(ns_parser, "sheet_name", None) @@ -192,7 +194,7 @@ class PlatformController(BaseController): ) except Exception as e: - Session().console.print(f"[red]{e}[/]\n") + session.console.print(f"[red]{e}[/]\n") return # Bind the method to the class @@ -278,13 +280,13 @@ class PlatformController(BaseController): command_description=command_description, ) - Session().console.print(text=mt.menu_text, menu=self._name) + session.console.print(text=mt.menu_text, menu=self._name) - settings = Session().settings + settings = session.settings dev_mode = settings.DEBUG_MODE or settings.TEST_MODE if mt.warnings and dev_mode: - Session().console.print("") + session.console.print("") for w in mt.warnings: w_str = str(w).replace("{", "").replace("}", "").replace("'", "") - Session().console.print(f"[yellow]{w_str}[/yellow]") - Session().console.print("") + session.console.print(f"[yellow]{w_str}[/yellow]") + session.console.print("") diff --git a/openbb_terminal/openbb_terminal/controllers/choices.py b/openbb_terminal/openbb_terminal/controllers/choices.py index ba3def5a3c2..681837a4529 100644 --- a/openbb_terminal/openbb_terminal/controllers/choices.py +++ b/openbb_terminal/openbb_terminal/controllers/choices.py @@ -13,6 +13,8 @@ from openbb_terminal.controllers.utils import ( ) from openbb_terminal.session import Session +session = Session() + def __mock_parse_known_args_and_warn( controller, # pylint: disable=unused-argument @@ -206,7 +208,7 @@ def __patch_controller_functions(controller): ), ] - if not Session().settings.DEBUG_MODE: + if not session.settings.DEBUG_MODE: rich.start() patched_function_list = [] for patcher in patcher_list: @@ -214,7 +216,7 @@ def __patch_controller_functions(controller): yield patched_function_list - if not Session().settings.DEBUG_MODE: + if not session.settings.DEBUG_MODE: rich.stop() for patcher in patcher_list: patcher.stop() @@ -314,7 +316,7 @@ def build_controller_choice_map(controller) -> dict: argument_parser=argument_parser ) except Exception as exception: - if Session().settings.DEBUG_MODE: + if session.settings.DEBUG_MODE: raise Exception( f"On command : `{command}`.\n{str(exception)}" ) from exception diff --git a/openbb_terminal/openbb_terminal/controllers/feature_flags_controller.py b/openbb_terminal/openbb_terminal/controllers/feature_flags_controller.py index c2761838920..b03b0060867 100644 --- a/openbb_terminal/openbb_terminal/controllers/feature_flags_controller.py +++ b/openbb_terminal/openbb_terminal/controllers/feature_flags_controller.py @@ -13,6 +13,8 @@ from openbb_terminal.controllers.base_controller import BaseController from openbb_terminal.controllers.utils import all_timezones, is_timezone_valid from openbb_terminal.session import Session +session = Session() + class FeatureFlagsController(BaseController): """Feature Flags Controller class.""" @@ -46,15 +48,13 @@ class FeatureFlagsController(BaseController): """Initialize the Constructor.""" super().__init__(queue) - self._session = Session() - - if self._session.prompt_session and self._session.settings.USE_PROMPT_TOOLKIT: + if session.prompt_session and session.settings.USE_PROMPT_TOOLKIT: choices: dict = self.choices_default self.completer = NestedCompleter.from_nested_dict(choices) def print_help(self): """Print help.""" - settings = self._session.settings + settings = session.settings mt = MenuText("settings/") mt.add_info("_info_") @@ -78,67 +78,61 @@ class FeatureFlagsController(BaseController): mt.add_cmd("n_rows") mt.add_cmd("n_cols") - self._session.console.print(text=mt.menu_text, menu="Feature Flags") + session.console.print(text=mt.menu_text, menu="Feature Flags") def call_overwrite(self, _): """Process overwrite command.""" - self._session.settings.set_item( - "FILE_OVERWRITE", not self._session.settings.FILE_OVERWRITE - ) + session.settings.set_item("FILE_OVERWRITE", not session.settings.FILE_OVERWRITE) def call_version(self, _): """Process version command.""" - self._session.settings.SHOW_VERSION = not self._session.settings.SHOW_VERSION + session.settings.SHOW_VERSION = not session.settings.SHOW_VERSION def call_interactive(self, _): """Process interactive command.""" - self._session.settings.set_item( - "USE_INTERACTIVE_DF", not self._session.settings.USE_INTERACTIVE_DF + session.settings.set_item( + "USE_INTERACTIVE_DF", not session.settings.USE_INTERACTIVE_DF ) def call_cls(self, _): """Process cls command.""" - self._session.settings.set_item( - "USE_CLEAR_AFTER_CMD", not self._session.settings.USE_CLEAR_AFTER_CMD + session.settings.set_item( + "USE_CLEAR_AFTER_CMD", not session.settings.USE_CLEAR_AFTER_CMD ) def call_promptkit(self, _): """Process promptkit command.""" - self._session.settings.set_item( - "USE_PROMPT_TOOLKIT", not self._session.settings.USE_PROMPT_TOOLKIT + session.settings.set_item( + "USE_PROMPT_TOOLKIT", not session.settings.USE_PROMPT_TOOLKIT ) def call_exithelp(self, _): """Process exithelp command.""" - self._session.settings.set_item( - "ENABLE_EXIT_AUTO_HELP", not self._session.settings.ENABLE_EXIT_AUTO_HELP + session.settings.set_item( + "ENABLE_EXIT_AUTO_HELP", not session.settings.ENABLE_EXIT_AUTO_HELP ) def call_rcontext(self, _): """Process rcontext command.""" - self._session.settings.set_item( - "REMEMBER_CONTEXTS", not self._session.settings.REMEMBER_CONTEXTS + session.settings.set_item( + "REMEMBER_CONTEXTS", not session.settings.REMEMBER_CONTEXTS ) def call_dt(self, _): """Process dt command.""" - self._session.settings.set_item( - "USE_DATETIME", not self._session.settings.USE_DATETIME - ) + session.settings.set_item("USE_DATETIME", not session.settings.USE_DATETIME) def call_richpanel(self, _): """Process richpanel command.""" - self._session.settings.set_item( - "ENABLE_RICH_PANEL", not self._session.settings.ENABLE_RICH_PANEL + session.settings.set_item( + "ENABLE_RICH_PANEL", not session.settings.ENABLE_RICH_PANEL ) def call_tbhint(self, _): """Process tbhint command.""" - if self._session.settings.TOOLBAR_HINT: - self._session.console.print("Will take effect when running terminal next.") - self._session.settings.set_item( - "TOOLBAR_HINT", not self._session.settings.TOOLBAR_HINT - ) + if session.settings.TOOLBAR_HINT: + session.console.print("Will take effect when running terminal next.") + session.settings.set_item("TOOLBAR_HINT", not session.settings.TOOLBAR_HINT) def call_console_style(self, other_args: List[str]) -> None: """Process cosole_style command.""" @@ -154,20 +148,20 @@ class FeatureFlagsController(BaseController): dest="style", action="store", required=False, - choices=self._session.style.available_styles, + choices=session.style.available_styles, ) ns_parser = self.parse_simple_args(parser, other_args) if ns_parser and ns_parser.style: - self._session.style.apply(ns_parser.style) - self._session.settings.set_item("RICH_STYLE", ns_parser.style) - self._session.console.print( - f"Console style changed to: {self._session.settings.RICH_STYLE}, run 'reset'" + session.style.apply(ns_parser.style) + session.settings.set_item("RICH_STYLE", ns_parser.style) + session.console.print( + f"Console style changed to: {session.settings.RICH_STYLE}, run 'reset'" " or restart the program to apply the changes." ) elif not other_args: - self._session.console.print( - f"Current console style: {self._session.settings.RICH_STYLE}" + session.console.print( + f"Current console style: {session.settings.RICH_STYLE}" ) def call_flair(self, other_args: List[str]) -> None: @@ -189,11 +183,9 @@ class FeatureFlagsController(BaseController): ns_parser = self.parse_simple_args(parser, other_args) if ns_parser and ns_parser.flair: - self._session.settings.set_item("FLAIR", ns_parser.flair) + session.settings.set_item("FLAIR", ns_parser.flair) elif not other_args: - self._session.console.print( - f"Current flair: {self._session.settings.FLAIR}" - ) + session.console.print(f"Current flair: {session.settings.FLAIR}") def call_timezone(self, other_args: List[str]) -> None: """Process timezone command.""" @@ -216,18 +208,16 @@ class FeatureFlagsController(BaseController): if ns_parser and ns_parser.timezone: if is_timezone_valid(ns_parser.timezone): - self._session.settings.set_item("TIMEZONE", ns_parser.timezone) + session.settings.set_item("TIMEZONE", ns_parser.timezone) else: - self._session.console.print( + session.console.print( "Invalid timezone. Please enter a v |