From bbaad2b303d7e354e08950699759906d1c00190d Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Tue, 11 Apr 2023 14:51:28 +0100 Subject: [PATCH 01/22] make default routines available --- openbb_terminal/account/account_controller.py | 145 ++++++++++++------ openbb_terminal/account/account_model.py | 23 ++- openbb_terminal/account/account_view.py | 35 ++++- openbb_terminal/core/session/hub_model.py | 34 +++- 4 files changed, 178 insertions(+), 59 deletions(-) diff --git a/openbb_terminal/account/account_controller.py b/openbb_terminal/account/account_controller.py index 53d7b60eeef1..6ba9b577bd27 100644 --- a/openbb_terminal/account/account_controller.py +++ b/openbb_terminal/account/account_controller.py @@ -4,12 +4,16 @@ from typing import Dict, List, Optional from openbb_terminal.account.account_model import ( + get_default_routines_info, get_routines_info, read_routine, save_routine, set_login_called, ) -from openbb_terminal.account.account_view import display_routines_list +from openbb_terminal.account.account_view import ( + display_default_routines_list, + display_routines_list, +) from openbb_terminal.core.session import hub_model as Hub from openbb_terminal.core.session.current_user import ( get_current_user, @@ -49,27 +53,41 @@ class AccountController(BaseController): def __init__(self, queue: Optional[List[str]] = None): """Constructor""" super().__init__(queue) - self.ROUTINE_FILES: Dict[str, Path] = {} + self.LOCAL_ROUTINES: Dict[str, Path] = {} self.REMOTE_CHOICES: List[str] = [] + + self.DEFAULT_ROUTINES: List[Dict[str, str]] = self.fetch_default_routines() + self.DEFAULT_CHOICES: List[str] = [ + r["name"] for r in self.DEFAULT_ROUTINES if "name" in r + ] + if session and get_current_user().preferences.USE_PROMPT_TOOLKIT: self.choices: dict = self.choices_default self.completer = NestedCompleter.from_nested_dict(self.choices) def update_runtime_choices(self): """Update runtime choices""" - self.ROUTINE_FILES = self.get_routines() + self.LOCAL_ROUTINES = self.get_local_routines() if session and get_current_user().preferences.USE_PROMPT_TOOLKIT: - self.choices["upload"]["--file"].update({c: {} for c in self.ROUTINE_FILES}) + self.choices["upload"]["--file"].update( + {c: {} for c in self.LOCAL_ROUTINES} + ) self.choices["download"]["--name"].update( - {c: {} for c in self.REMOTE_CHOICES} + {c: {} for c in self.DEFAULT_CHOICES + self.REMOTE_CHOICES} ) self.choices["delete"]["--name"].update( {c: {} for c in self.REMOTE_CHOICES} ) self.completer = NestedCompleter.from_nested_dict(self.choices) - def get_routines(self): - """Get routines""" + def get_local_routines(self) -> Dict[str, Path]: + """Get local routines + + Returns + ------- + Dict[str, Path] + The local routines + """ current_user = get_current_user() return { filepath.name: filepath @@ -78,6 +96,20 @@ def get_routines(self): ) } + def fetch_default_routines(self) -> List[Dict[str, str]]: + """Fetch default routines + + Returns + ------- + List[Dict[str, str]] + The default routines + """ + response = Hub.get_default_routines() + if response.status_code == 200: + d = response.json() + return d.get("data", []) + return [] + def print_help(self): """Print help""" mt = MenuText("account/", 100) @@ -196,12 +228,12 @@ def call_list(self, other_args: List[str]): print_guest_block_msg() else: if ns_parser: - response = Hub.list_routines( + user_response = Hub.list_routines( auth_header=get_current_user().profile.get_auth_header(), page=ns_parser.page, size=ns_parser.size, ) - df, page, pages = get_routines_info(response) + df, page, pages = get_routines_info(user_response) if not df.empty: self.REMOTE_CHOICES += list(df["name"]) self.update_runtime_choices() @@ -209,6 +241,9 @@ def call_list(self, other_args: List[str]): else: console.print("[red]No routines found.[/red]") + df = get_default_routines_info(self.DEFAULT_ROUTINES) + display_default_routines_list(df) + @log_start_end(log=logger) def call_upload(self, other_args: List[str]): """Upload""" @@ -320,49 +355,61 @@ def call_download(self, other_args: List[str]): print_guest_block_msg() else: if ns_parser: - response = Hub.download_routine( - auth_header=get_current_user().profile.get_auth_header(), - name=" ".join(ns_parser.name), - ) + data = None - if response and response.status_code == 200: - data = response.json() - if data: - name = data.get("name", "") - if name: - console.print(f"[info]Name:[/info] {name}") - - description = data.get("description", "") - if description: - console.print(f"[info]Description:[/info] {description}") - - script = data.get("script", "") - if script: - file_name = f"{name}.openbb" - file_path = save_routine( - file_name=file_name, - routine=script, + # Default routine + name = " ".join(ns_parser.name) + if name in self.DEFAULT_CHOICES: + data = next( + (r for r in self.DEFAULT_ROUTINES if r["name"] == name), None + ) + else: + # User routine + response = Hub.download_routine( + auth_header=get_current_user().profile.get_auth_header(), + name=name, + ) + data = ( + response.json() + if response and response.status_code == 200 + else None + ) + + # Save routine + if data: + name = data.get("name", "") + if name: + console.print(f"[info]Name:[/info] {name}") + + description = data.get("description", "") + if description: + console.print(f"[info]Description:[/info] {description}") + + script = data.get("script", "") + if script: + file_name = f"{name}.openbb" + file_path = save_routine( + file_name=file_name, + routine=script, + ) + if file_path == "File already exists": + i = console.input( + "\nA file with the same name already exists, " + "do you want to replace it? (y/n): " ) - if file_path == "File already exists": - i = console.input( - "\nA file with the same name already exists, " - "do you want to replace it? (y/n): " + console.print("") + if i.lower() in ["y", "yes"]: + file_path = save_routine( + file_name=file_name, + routine=script, + force=True, ) - console.print("") - if i.lower() in ["y", "yes"]: - file_path = save_routine( - file_name=file_name, - routine=script, - force=True, - ) - if file_path: - console.print( - f"[info]Location:[/info] {file_path}" - ) - else: - console.print("[info]Aborted.[/info]") - elif file_path: - console.print(f"[info]Location:[/info] {file_path}") + if file_path: + console.print(f"[info]Location:[/info] {file_path}") + else: + console.print("[info]Aborted.[/info]") + elif file_path: + console.print(f"[info]Location:[/info] {file_path}") @log_start_end(log=logger) def call_delete(self, other_args: List[str]): diff --git a/openbb_terminal/account/account_model.py b/openbb_terminal/account/account_model.py index 3c7543f6ca3f..fc964bafd926 100644 --- a/openbb_terminal/account/account_model.py +++ b/openbb_terminal/account/account_model.py @@ -1,6 +1,6 @@ import os from pathlib import Path -from typing import Optional, Tuple, Union +from typing import Dict, List, Optional, Tuple, Union import numpy as np import pandas as pd @@ -34,6 +34,27 @@ def set_login_called(value: bool): __login_called = value +def get_default_routines_info(routines: List[Dict[str, str]]) -> pd.DataFrame: + """Get the routines list. + + Parameters + ---------- + response : requests.Response + The response. + + Returns + ------- + Tuple[pd.DataFrame, int, int] + The routines list, the current page and the total number of pages. + """ + df = pd.DataFrame() + if routines: + df = pd.DataFrame(routines) + df = df[["name", "description", "version"]] + df.index = np.arange(1, len(df) + 1) + return df + + def get_routines_info(response) -> Tuple[pd.DataFrame, int, int]: """Get the routines list. diff --git a/openbb_terminal/account/account_view.py b/openbb_terminal/account/account_view.py index f9c7bcd1c261..781c9daf4043 100644 --- a/openbb_terminal/account/account_view.py +++ b/openbb_terminal/account/account_view.py @@ -15,14 +15,33 @@ def display_routines_list(df: pd.DataFrame, page: int, pages: int): pages : int The total number of pages. """ - title = f"Available routines - page {page}" + title = f"User routines - page {page}" if pages: title += f" of {pages}" - print_rich_table( - df=df, - title=title, - headers=["Name", "Description"], - show_index=True, - index_name="#", - ) + if all(c in df.columns for c in ["name", "description", "version"]): + print_rich_table( + df=df, + title=title, + headers=["Name", "Description", "Version"], + show_index=True, + index_name="#", + ) + + +def display_default_routines_list(df: pd.DataFrame): + """Display the default routines list. + + Parameters + ---------- + df : pd.DataFrame + The default routines list. + """ + if all(c in df.columns for c in ["name", "description", "version"]): + print_rich_table( + df=df, + title="Default routines", + headers=["Name", "Description", "Version"], + show_index=True, + index_name="#", + ) diff --git a/openbb_terminal/core/session/hub_model.py b/openbb_terminal/core/session/hub_model.py index 618c5b4224bc..e435a84c44a8 100644 --- a/openbb_terminal/core/session/hub_model.py +++ b/openbb_terminal/core/session/hub_model.py @@ -581,7 +581,7 @@ def list_routines( Optional[requests.Response] The response from the get request. """ - fields = "name%2Cdescription" + fields = "name%2Cdescription%2Cversion" try: response = requests.get( @@ -603,6 +603,38 @@ def list_routines( return None +def get_default_routines(timeout: int = TIMEOUT): + """Get the default routines from CMS. + + Parameters + ---------- + timeout : int + The timeout, by default TIMEOUT + + Returns + ------- + Optional[requests.Response] + The response from the get request. + """ + try: + response = requests.get( + url="https://tffo1zc1.directus.app/items/Routines", + timeout=timeout, + ) + if response.status_code != 200: + console.print("[red]Failed to get default routines.[/red]") + return response + except requests.exceptions.ConnectionError: + console.print(f"\n{CONNECTION_ERROR_MSG}") + return None + except requests.exceptions.Timeout: + console.print(f"\n{CONNECTION_TIMEOUT_MSG}") + return None + except Exception: + console.print("[red]Failed to get default routines.[/red]") + return None + + def generate_personal_access_token( auth_header: str, base_url: str = BASE_URL, timeout: int = TIMEOUT, days: int = 30 ) -> Optional[requests.Response]: From b4a4560e279c9a5e6b5c5b17cc66f6652240ce1f Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Tue, 11 Apr 2023 14:54:48 +0100 Subject: [PATCH 02/22] remove unecessary change --- openbb_terminal/account/account_controller.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openbb_terminal/account/account_controller.py b/openbb_terminal/account/account_controller.py index 6ba9b577bd27..0953d34945c2 100644 --- a/openbb_terminal/account/account_controller.py +++ b/openbb_terminal/account/account_controller.py @@ -228,12 +228,12 @@ def call_list(self, other_args: List[str]): print_guest_block_msg() else: if ns_parser: - user_response = Hub.list_routines( + response = Hub.list_routines( auth_header=get_current_user().profile.get_auth_header(), page=ns_parser.page, size=ns_parser.size, ) - df, page, pages = get_routines_info(user_response) + df, page, pages = get_routines_info(response) if not df.empty: self.REMOTE_CHOICES += list(df["name"]) self.update_runtime_choices() From bfae6854b548ee4ad6f9484492762de724862f80 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Tue, 11 Apr 2023 14:58:06 +0100 Subject: [PATCH 03/22] user to personal --- openbb_terminal/account/account_view.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openbb_terminal/account/account_view.py b/openbb_terminal/account/account_view.py index 781c9daf4043..25ecf567002e 100644 --- a/openbb_terminal/account/account_view.py +++ b/openbb_terminal/account/account_view.py @@ -15,7 +15,7 @@ def display_routines_list(df: pd.DataFrame, page: int, pages: int): pages : int The total number of pages. """ - title = f"User routines - page {page}" + title = f"Personal routines - page {page}" if pages: title += f" of {pages}" From d915e6f02a9fc72ecda170ee615fde774a531649 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Tue, 11 Apr 2023 15:08:12 +0100 Subject: [PATCH 04/22] rename some funcs --- openbb_terminal/account/account_controller.py | 12 ++++++------ openbb_terminal/account/account_model.py | 2 +- openbb_terminal/account/account_view.py | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/openbb_terminal/account/account_controller.py b/openbb_terminal/account/account_controller.py index 0953d34945c2..30487132108f 100644 --- a/openbb_terminal/account/account_controller.py +++ b/openbb_terminal/account/account_controller.py @@ -5,14 +5,14 @@ from openbb_terminal.account.account_model import ( get_default_routines_info, - get_routines_info, + get_personal_routines_info, read_routine, save_routine, set_login_called, ) from openbb_terminal.account.account_view import ( - display_default_routines_list, - display_routines_list, + display_default_routines, + display_personal_routines, ) from openbb_terminal.core.session import hub_model as Hub from openbb_terminal.core.session.current_user import ( @@ -233,16 +233,16 @@ def call_list(self, other_args: List[str]): page=ns_parser.page, size=ns_parser.size, ) - df, page, pages = get_routines_info(response) + df, page, pages = get_personal_routines_info(response) if not df.empty: self.REMOTE_CHOICES += list(df["name"]) self.update_runtime_choices() - display_routines_list(df, page, pages) + display_personal_routines(df, page, pages) else: console.print("[red]No routines found.[/red]") df = get_default_routines_info(self.DEFAULT_ROUTINES) - display_default_routines_list(df) + display_default_routines(df) @log_start_end(log=logger) def call_upload(self, other_args: List[str]): diff --git a/openbb_terminal/account/account_model.py b/openbb_terminal/account/account_model.py index fc964bafd926..4311398de798 100644 --- a/openbb_terminal/account/account_model.py +++ b/openbb_terminal/account/account_model.py @@ -55,7 +55,7 @@ def get_default_routines_info(routines: List[Dict[str, str]]) -> pd.DataFrame: return df -def get_routines_info(response) -> Tuple[pd.DataFrame, int, int]: +def get_personal_routines_info(response) -> Tuple[pd.DataFrame, int, int]: """Get the routines list. Parameters diff --git a/openbb_terminal/account/account_view.py b/openbb_terminal/account/account_view.py index 25ecf567002e..e82133c86586 100644 --- a/openbb_terminal/account/account_view.py +++ b/openbb_terminal/account/account_view.py @@ -3,8 +3,8 @@ from openbb_terminal.helper_funcs import print_rich_table -def display_routines_list(df: pd.DataFrame, page: int, pages: int): - """Display the routines list. +def display_personal_routines(df: pd.DataFrame, page: int, pages: int): + """Display the routines. Parameters ---------- @@ -29,8 +29,8 @@ def display_routines_list(df: pd.DataFrame, page: int, pages: int): ) -def display_default_routines_list(df: pd.DataFrame): - """Display the default routines list. +def display_default_routines(df: pd.DataFrame): + """Display the default routines. Parameters ---------- From 55194bbbf276985dd38d43c8855bb3c4787cff12 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Tue, 11 Apr 2023 15:53:15 +0100 Subject: [PATCH 05/22] add last update to tables --- openbb_terminal/account/account_model.py | 2 +- openbb_terminal/account/account_view.py | 14 ++++++++++---- openbb_terminal/core/session/hub_model.py | 2 +- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/openbb_terminal/account/account_model.py b/openbb_terminal/account/account_model.py index 4311398de798..299eb274f960 100644 --- a/openbb_terminal/account/account_model.py +++ b/openbb_terminal/account/account_model.py @@ -50,7 +50,7 @@ def get_default_routines_info(routines: List[Dict[str, str]]) -> pd.DataFrame: df = pd.DataFrame() if routines: df = pd.DataFrame(routines) - df = df[["name", "description", "version"]] + df = df[["name", "description", "version", "date_updated"]] df.index = np.arange(1, len(df) + 1) return df diff --git a/openbb_terminal/account/account_view.py b/openbb_terminal/account/account_view.py index e82133c86586..1f8370b929ae 100644 --- a/openbb_terminal/account/account_view.py +++ b/openbb_terminal/account/account_view.py @@ -19,11 +19,14 @@ def display_personal_routines(df: pd.DataFrame, page: int, pages: int): if pages: title += f" of {pages}" - if all(c in df.columns for c in ["name", "description", "version"]): + if all(c in df.columns for c in ["name", "description", "version", "updated_date"]): + df["updated_date"] = pd.to_datetime(df["updated_date"]) + df["updated_date"] = df["updated_date"].dt.strftime("%Y-%m-%d %H:%M:%S") + df.replace(to_replace=[None], value="-", inplace=True) print_rich_table( df=df, title=title, - headers=["Name", "Description", "Version"], + headers=["Name", "Description", "Version", "Last update"], show_index=True, index_name="#", ) @@ -37,11 +40,14 @@ def display_default_routines(df: pd.DataFrame): df : pd.DataFrame The default routines list. """ - if all(c in df.columns for c in ["name", "description", "version"]): + if all(c in df.columns for c in ["name", "description", "version", "date_updated"]): + df["date_updated"] = pd.to_datetime(df["date_updated"]) + df["date_updated"] = df["date_updated"].dt.strftime("%Y-%m-%d %H:%M:%S") + df.replace(to_replace=[None], value="-", inplace=True) print_rich_table( df=df, title="Default routines", - headers=["Name", "Description", "Version"], + headers=["Name", "Description", "Version", "Last update"], show_index=True, index_name="#", ) diff --git a/openbb_terminal/core/session/hub_model.py b/openbb_terminal/core/session/hub_model.py index e435a84c44a8..63b5b2bca220 100644 --- a/openbb_terminal/core/session/hub_model.py +++ b/openbb_terminal/core/session/hub_model.py @@ -581,7 +581,7 @@ def list_routines( Optional[requests.Response] The response from the get request. """ - fields = "name%2Cdescription%2Cversion" + fields = "name%2Cdescription%2Cversion%2Cupdated_date" try: response = requests.get( From 26d448e95b9310b37e2ff50a831e8216853f96d4 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Tue, 11 Apr 2023 22:17:07 +0100 Subject: [PATCH 06/22] add routines download on login --- openbb_terminal/core/session/hub_model.py | 3 +- openbb_terminal/core/session/local_model.py | 13 +++-- .../core/session/routines_handler.py | 57 +++++++++++++++++++ openbb_terminal/core/session/session_model.py | 12 ++-- openbb_terminal/core/session/utils.py | 2 +- 5 files changed, 76 insertions(+), 11 deletions(-) create mode 100644 openbb_terminal/core/session/routines_handler.py diff --git a/openbb_terminal/core/session/hub_model.py b/openbb_terminal/core/session/hub_model.py index 63b5b2bca220..d669862859e5 100644 --- a/openbb_terminal/core/session/hub_model.py +++ b/openbb_terminal/core/session/hub_model.py @@ -556,6 +556,7 @@ def delete_routine( def list_routines( auth_header: str, + fields: str = "name%2Cdescription%2Cversion%2Cupdated_date", page: int = 1, size: int = 10, base_url=BASE_URL, @@ -581,8 +582,6 @@ def list_routines( Optional[requests.Response] The response from the get request. """ - fields = "name%2Cdescription%2Cversion%2Cupdated_date" - try: response = requests.get( headers={"Authorization": auth_header}, diff --git a/openbb_terminal/core/session/local_model.py b/openbb_terminal/core/session/local_model.py index f5b5c4f02b38..8a497560791e 100644 --- a/openbb_terminal/core/session/local_model.py +++ b/openbb_terminal/core/session/local_model.py @@ -10,7 +10,6 @@ ) from openbb_terminal.core.models.sources_model import get_allowed_sources from openbb_terminal.core.session.current_user import ( - get_current_user, get_env_dict, set_credential, set_preference, @@ -87,11 +86,17 @@ def remove(path: Path) -> bool: return False -def update_flair(): - """Update the flair.""" +def update_flair(username: str): + """Update the flair. + + Parameters + ---------- + username : str + The username. + """ if "FLAIR" not in get_env_dict(): MAX_FLAIR_LEN = 20 - flair = "[" + get_current_user().profile.username[:MAX_FLAIR_LEN] + "]" + " 🦋" + flair = "[" + username[:MAX_FLAIR_LEN] + "]" + " 🦋" set_preference("FLAIR", flair) diff --git a/openbb_terminal/core/session/routines_handler.py b/openbb_terminal/core/session/routines_handler.py new file mode 100644 index 000000000000..725801c730dc --- /dev/null +++ b/openbb_terminal/core/session/routines_handler.py @@ -0,0 +1,57 @@ +from typing import Dict + +import openbb_terminal.core.session.hub_model as Hub +from openbb_terminal.account.account_model import save_routine + +# move all routines stuff here + + +def download_routines( + auth_header: str, +) -> Dict[str, str]: + """Download a routine from the server. + + Parameters + ---------- + auth_header : str + The authorization header, e.g. "Bearer ". + + Returns + ------- + Dict[str, str] + The routines. + """ + routines_dict = {} + + fields = "name%2Cscript" + response = Hub.list_routines(auth_header, fields=fields, page=1, size=100) + if response and response.status_code == 200: + content = response.json() + items = content.get("items", []) + for routine in items: + name = routine.get("name", "") + if name: + routines_dict[name] = routine.get("script", "") + + response = Hub.get_default_routines() + if response and response.status_code == 200: + content = response.json() + data = content.get("data", []) + for routine in data: + name = routine.get("name", "") + if name: + routines_dict[name] = routine.get("script", "") + return routines_dict + + +def download_and_save_routines(auth_header: str): + """Download and save routines. + + Parameters + ---------- + auth_header : str + The authorization header, e.g. "Bearer ". + """ + routines = download_routines(auth_header) + for name, content in routines.items(): + save_routine(file_name=f"{name}.openbb", routine=content, force=True) diff --git a/openbb_terminal/core/session/session_model.py b/openbb_terminal/core/session/session_model.py index 9c5bf9b64a11..616cc9176be6 100644 --- a/openbb_terminal/core/session/session_model.py +++ b/openbb_terminal/core/session/session_model.py @@ -21,6 +21,7 @@ set_current_user, set_default_user, ) +from openbb_terminal.core.session.routines_handler import download_and_save_routines from openbb_terminal.core.session.sources_handler import get_updated_hub_sources from openbb_terminal.core.session.utils import run_thread from openbb_terminal.helper_funcs import system_clear @@ -100,10 +101,8 @@ def login(session: dict) -> LoginStatus: email = configs.get("email", "") hub_user.profile.load_user_info(session, email) set_current_user(hub_user) - Local.apply_configs(configs=configs) - Local.update_flair() - # Update user sources in backend + auth_header = hub_user.profile.get_auth_header() updated_sources = get_updated_hub_sources(configs) if updated_sources: run_thread( @@ -111,10 +110,15 @@ def login(session: dict) -> LoginStatus: { "key": "features_sources", "value": updated_sources, - "auth_header": get_current_user().profile.get_auth_header(), + "auth_header": auth_header, "silent": True, }, ) + run_thread(download_and_save_routines, {"auth_header": auth_header}) + + Local.apply_configs(configs) + Local.update_flair(get_current_user().profile.username) + return LoginStatus.SUCCESS if response.status_code == 401: return LoginStatus.UNAUTHORIZED diff --git a/openbb_terminal/core/session/utils.py b/openbb_terminal/core/session/utils.py index 04582817475a..5d4da8601aa6 100644 --- a/openbb_terminal/core/session/utils.py +++ b/openbb_terminal/core/session/utils.py @@ -54,5 +54,5 @@ def run_thread(target, kwargs): args : tuple The arguments. """ - thread = Thread(target=target, kwargs=kwargs) + thread = Thread(target=target, kwargs=kwargs, daemon=True) thread.start() From e0f9818b27e9b2d3ad6ad40d8934efb9b8566a64 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Tue, 11 Apr 2023 23:12:49 +0100 Subject: [PATCH 07/22] move some routines funcs to controller --- openbb_terminal/account/__init__.py | 0 openbb_terminal/account/account_controller.py | 41 ++++- openbb_terminal/account/account_model.py | 166 ------------------ openbb_terminal/core/session/__init__.py | 0 .../core/session/routines_handler.py | 147 +++++++++++++++- openbb_terminal/terminal_controller.py | 2 +- 6 files changed, 177 insertions(+), 179 deletions(-) create mode 100644 openbb_terminal/account/__init__.py delete mode 100644 openbb_terminal/account/account_model.py create mode 100644 openbb_terminal/core/session/__init__.py diff --git a/openbb_terminal/account/__init__.py b/openbb_terminal/account/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/openbb_terminal/account/account_controller.py b/openbb_terminal/account/account_controller.py index 30487132108f..defb6b229c4d 100644 --- a/openbb_terminal/account/account_controller.py +++ b/openbb_terminal/account/account_controller.py @@ -3,13 +3,6 @@ from pathlib import Path from typing import Dict, List, Optional -from openbb_terminal.account.account_model import ( - get_default_routines_info, - get_personal_routines_info, - read_routine, - save_routine, - set_login_called, -) from openbb_terminal.account.account_view import ( display_default_routines, display_personal_routines, @@ -19,6 +12,12 @@ get_current_user, is_local, ) +from openbb_terminal.core.session.routines_handler import ( + get_default_routines_info, + get_personal_routines_info, + read_routine, + save_routine, +) from openbb_terminal.core.session.session_model import logout from openbb_terminal.custom_prompt_toolkit import NestedCompleter from openbb_terminal.decorators import log_start_end @@ -31,6 +30,32 @@ logger = logging.getLogger(__name__) +__login_called = False + + +def get_login_called(): + """Get the login/logout called flag. + + Returns + ------- + bool + The login/logout called flag. + """ + return __login_called + + +def set_login_called(value: bool): + """Set the login/logout called flag. + + Parameters + ---------- + value : bool + The login/logout called flag. + """ + global __login_called # pylint: disable=global-statement + __login_called = value + + class AccountController(BaseController): """Account Controller Class""" @@ -105,7 +130,7 @@ def fetch_default_routines(self) -> List[Dict[str, str]]: The default routines """ response = Hub.get_default_routines() - if response.status_code == 200: + if response and response.status_code == 200: d = response.json() return d.get("data", []) return [] diff --git a/openbb_terminal/account/account_model.py b/openbb_terminal/account/account_model.py deleted file mode 100644 index 299eb274f960..000000000000 --- a/openbb_terminal/account/account_model.py +++ /dev/null @@ -1,166 +0,0 @@ -import os -from pathlib import Path -from typing import Dict, List, Optional, Tuple, Union - -import numpy as np -import pandas as pd - -from openbb_terminal.core.session.current_user import get_current_user -from openbb_terminal.rich_config import console - -__login_called = False - - -def get_login_called(): - """Get the login/logout called flag. - - Returns - ------- - bool - The login/logout called flag. - """ - return __login_called - - -def set_login_called(value: bool): - """Set the login/logout called flag. - - Parameters - ---------- - value : bool - The login/logout called flag. - """ - global __login_called # pylint: disable=global-statement - __login_called = value - - -def get_default_routines_info(routines: List[Dict[str, str]]) -> pd.DataFrame: - """Get the routines list. - - Parameters - ---------- - response : requests.Response - The response. - - Returns - ------- - Tuple[pd.DataFrame, int, int] - The routines list, the current page and the total number of pages. - """ - df = pd.DataFrame() - if routines: - df = pd.DataFrame(routines) - df = df[["name", "description", "version", "date_updated"]] - df.index = np.arange(1, len(df) + 1) - return df - - -def get_personal_routines_info(response) -> Tuple[pd.DataFrame, int, int]: - """Get the routines list. - - Parameters - ---------- - response : requests.Response - The response. - - Returns - ------- - Tuple[pd.DataFrame, int, int] - The routines list, the current page and the total number of pages. - """ - df = pd.DataFrame() - page = 1 - pages = 1 - if response and response.status_code == 200: - data = response.json() - page = data.get("page", 1) - pages = data.get("pages", 1) - items = data.get("items", []) - if items: - df = pd.DataFrame(items) - df.index = np.arange(1, len(df) + 1) - - return df, page, pages - - -def read_routine(file_name: str, folder: Optional[Path] = None) -> Optional[str]: - """Read the routine. - - Parameters - ---------- - file_name : str - The routine. - folder : Optional[Path] - The routines folder. - - Returns - ------- - file_name : str - The routine. - folder : Optional[Path] - The routines folder. - """ - - current_user = get_current_user() - if folder is None: - folder = current_user.preferences.USER_ROUTINES_DIRECTORY - - try: - user_folder = folder / "hub" - file_path = ( - user_folder / file_name - if os.path.exists(user_folder / file_name) - else folder / file_name - ) - - with open(file_path) as f: - routine = "".join(f.readlines()) - return routine - except Exception: - console.print("[red]Failed to find routine.[/red]") - return None - - -def save_routine( - file_name: str, - routine: str, - folder: Optional[Path] = None, - force: bool = False, -) -> Union[Optional[Path], str]: - """Save the routine. - - Parameters - ---------- - file_name : str - The routine. - routine : str - The routine. - folder : Path - The routines folder. - force : bool - Force the save. - - Returns - ------- - Optional[Path, str] - The path to the routine or None. - """ - - current_user = get_current_user() - if folder is None: - folder = current_user.preferences.USER_ROUTINES_DIRECTORY - - try: - user_folder = folder / "hub" - if not os.path.exists(user_folder): - os.makedirs(user_folder) - - file_path = user_folder / file_name - if os.path.exists(file_path) and not force: - return "File already exists" - with open(file_path, "w") as f: - f.write(routine) - return user_folder / file_name - except Exception: - console.print("[red]\nFailed to save routine.[/red]") - return None diff --git a/openbb_terminal/core/session/__init__.py b/openbb_terminal/core/session/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/openbb_terminal/core/session/routines_handler.py b/openbb_terminal/core/session/routines_handler.py index 725801c730dc..d6e13627b3e0 100644 --- a/openbb_terminal/core/session/routines_handler.py +++ b/openbb_terminal/core/session/routines_handler.py @@ -1,9 +1,13 @@ -from typing import Dict +import os +from pathlib import Path +from typing import Dict, List, Optional, Tuple, Union -import openbb_terminal.core.session.hub_model as Hub -from openbb_terminal.account.account_model import save_routine +import numpy as np +import pandas as pd -# move all routines stuff here +import openbb_terminal.core.session.hub_model as Hub +from openbb_terminal.core.session.current_user import get_current_user +from openbb_terminal.rich_config import console def download_routines( @@ -55,3 +59,138 @@ def download_and_save_routines(auth_header: str): routines = download_routines(auth_header) for name, content in routines.items(): save_routine(file_name=f"{name}.openbb", routine=content, force=True) + + +def read_routine(file_name: str, folder: Optional[Path] = None) -> Optional[str]: + """Read the routine. + + Parameters + ---------- + file_name : str + The routine. + folder : Optional[Path] + The routines folder. + + Returns + ------- + file_name : str + The routine. + folder : Optional[Path] + The routines folder. + """ + + current_user = get_current_user() + if folder is None: + folder = current_user.preferences.USER_ROUTINES_DIRECTORY + + try: + user_folder = folder / "hub" + file_path = ( + user_folder / file_name + if os.path.exists(user_folder / file_name) + else folder / file_name + ) + + with open(file_path) as f: + routine = "".join(f.readlines()) + return routine + except Exception: + console.print("[red]Failed to find routine.[/red]") + return None + + +def save_routine( + file_name: str, + routine: str, + folder: Optional[Path] = None, + force: bool = False, +) -> Union[Optional[Path], str]: + """Save the routine. + + Parameters + ---------- + file_name : str + The routine. + routine : str + The routine. + folder : Path + The routines folder. + force : bool + Force the save. + + Returns + ------- + Optional[Path, str] + The path to the routine or None. + """ + + current_user = get_current_user() + if folder is None: + folder = current_user.preferences.USER_ROUTINES_DIRECTORY + + try: + user_folder = folder / "hub" + if not os.path.exists(user_folder): + os.makedirs(user_folder) + + file_path = user_folder / file_name + if os.path.exists(file_path) and not force: + return "File already exists" + with open(file_path, "w") as f: + f.write(routine) + return user_folder / file_name + except Exception: + console.print("[red]\nFailed to save routine.[/red]") + return None + + +def get_default_routines_info(routines: List[Dict[str, str]]) -> pd.DataFrame: + """Get the routines list. + + Parameters + ---------- + response : requests.Response + The response. + + Returns + ------- + Tuple[pd.DataFrame, int, int] + The routines list, the current page and the total number of pages. + """ + df = pd.DataFrame() + if routines: + df = pd.DataFrame(routines) + if all( + c in df.columns for c in ["name", "description", "version", "date_updated"] + ): + df = df[["name", "description", "version", "date_updated"]] + df.index = np.arange(1, len(df) + 1) + return df + + +def get_personal_routines_info(response) -> Tuple[pd.DataFrame, int, int]: + """Get the routines list. + + Parameters + ---------- + response : requests.Response + The response. + + Returns + ------- + Tuple[pd.DataFrame, int, int] + The routines list, the current page and the total number of pages. + """ + df = pd.DataFrame() + page = 1 + pages = 1 + if response and response.status_code == 200: + data = response.json() + page = data.get("page", 1) + pages = data.get("pages", 1) + items = data.get("items", []) + if items: + df = pd.DataFrame(items) + df.index = np.arange(1, len(df) + 1) + + return df, page, pages diff --git a/openbb_terminal/terminal_controller.py b/openbb_terminal/terminal_controller.py index af90c146fe51..498ff09d83f1 100644 --- a/openbb_terminal/terminal_controller.py +++ b/openbb_terminal/terminal_controller.py @@ -24,7 +24,7 @@ from rich import panel import openbb_terminal.config_terminal as cfg -from openbb_terminal.account.account_model import ( +from openbb_terminal.account.account_controller import ( get_login_called, set_login_called, ) From 6db14b35b429a3fdac41dc962dd6b101384ac6b0 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Tue, 11 Apr 2023 23:13:03 +0100 Subject: [PATCH 08/22] fix tests --- .../account/test_account_controller.py | 13 +++++++++++-- .../txt/test_account_controller/test_call_list.txt | 4 ---- .../test_call_sync[other_args0-False].txt | 1 - .../test_call_sync[other_args1-True].txt | 1 - .../test_call_sync[other_args2-True].txt | 1 - .../test_call_sync[other_args3-False].txt | 1 - .../test_call_sync[other_args4-True].txt | 1 - tests/openbb_terminal/session/test_hub_model.py | 2 +- .../test_routines_handler.py} | 10 +++++----- 9 files changed, 17 insertions(+), 17 deletions(-) delete mode 100644 tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args0-False].txt delete mode 100644 tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args1-True].txt delete mode 100644 tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args2-True].txt delete mode 100644 tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args3-False].txt delete mode 100644 tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args4-True].txt rename tests/openbb_terminal/{account/test_account_model.py => session/test_routines_handler.py} (92%) diff --git a/tests/openbb_terminal/account/test_account_controller.py b/tests/openbb_terminal/account/test_account_controller.py index c263f31097ea..36b217da63c0 100644 --- a/tests/openbb_terminal/account/test_account_controller.py +++ b/tests/openbb_terminal/account/test_account_controller.py @@ -70,6 +70,14 @@ def vcr_config(): } +@pytest.fixture(autouse=True) +def fetch_routines(mocker): + path_controller = "openbb_terminal.account.account_controller" + mocker.patch( + target=f"{path_controller}.AccountController.fetch_default_routines", + ) + + @pytest.fixture(name="test_user") def fixture_test_user(mocker): mocker.patch( @@ -187,11 +195,12 @@ def __call__(self, *args, **kwargs): @pytest.mark.vcr(record_mode="none") @pytest.mark.record_stdout def test_print_help(mocker, test_user): - controller = account_controller.AccountController(queue=None) + path_controller = "openbb_terminal.account.account_controller" mocker.patch( - target="openbb_terminal.account.account_controller.get_current_user", + target=f"{path_controller}.get_current_user", return_value=test_user, ) + controller = account_controller.AccountController(queue=None) controller.print_help() diff --git a/tests/openbb_terminal/account/txt/test_account_controller/test_call_list.txt b/tests/openbb_terminal/account/txt/test_account_controller/test_call_list.txt index d550119c1f93..e69de29bb2d1 100644 --- a/tests/openbb_terminal/account/txt/test_account_controller/test_call_list.txt +++ b/tests/openbb_terminal/account/txt/test_account_controller/test_call_list.txt @@ -1,4 +0,0 @@ - name description -1 scrip1 abc -2 script2 def -3 script3 ghi diff --git a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args0-False].txt b/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args0-False].txt deleted file mode 100644 index 4edd4cdac07b..000000000000 --- a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args0-False].txt +++ /dev/null @@ -1 +0,0 @@ -[info]sync:[/info] OFF diff --git a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args1-True].txt b/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args1-True].txt deleted file mode 100644 index 2be0167f17b4..000000000000 --- a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args1-True].txt +++ /dev/null @@ -1 +0,0 @@ -[info]sync:[/info] ON diff --git a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args2-True].txt b/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args2-True].txt deleted file mode 100644 index 2be0167f17b4..000000000000 --- a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args2-True].txt +++ /dev/null @@ -1 +0,0 @@ -[info]sync:[/info] ON diff --git a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args3-False].txt b/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args3-False].txt deleted file mode 100644 index 4edd4cdac07b..000000000000 --- a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args3-False].txt +++ /dev/null @@ -1 +0,0 @@ -[info]sync:[/info] OFF diff --git a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args4-True].txt b/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args4-True].txt deleted file mode 100644 index e7dcaab864b1..000000000000 --- a/tests/openbb_terminal/account/txt/test_account_controller/test_call_sync[other_args4-True].txt +++ /dev/null @@ -1 +0,0 @@ -sync is ON, use --on or --off to change. diff --git a/tests/openbb_terminal/session/test_hub_model.py b/tests/openbb_terminal/session/test_hub_model.py index f915a59ddae2..1b065f74de69 100644 --- a/tests/openbb_terminal/session/test_hub_model.py +++ b/tests/openbb_terminal/session/test_hub_model.py @@ -703,7 +703,7 @@ def test_list_routines(auth_header, page, size, base_url, timeout, status_code): assert ( kwargs["url"] == base_url - + f"terminal/script?fields=name%2Cdescription&page={page}&size={size}" + + f"terminal/script?fields=name%2Cdescription%2Cversion%2Cupdated_date&page={page}&size={size}" ) assert kwargs["headers"] == {"Authorization": auth_header} assert kwargs["timeout"] == timeout diff --git a/tests/openbb_terminal/account/test_account_model.py b/tests/openbb_terminal/session/test_routines_handler.py similarity index 92% rename from tests/openbb_terminal/account/test_account_model.py rename to tests/openbb_terminal/session/test_routines_handler.py index 4e2306cd2ef0..8ea78b16ebe0 100644 --- a/tests/openbb_terminal/account/test_account_model.py +++ b/tests/openbb_terminal/session/test_routines_handler.py @@ -8,7 +8,6 @@ import pytest # IMPORTATION INTERNAL -from openbb_terminal.account.account_model import read_routine, save_routine from openbb_terminal.core.models.user_model import ( CredentialsModel, PreferencesModel, @@ -17,6 +16,7 @@ UserModel, ) from openbb_terminal.core.session.current_user import get_current_user +from openbb_terminal.core.session.routines_handler import read_routine, save_routine @pytest.fixture(name="test_user") @@ -40,7 +40,7 @@ def test_read_routine(mocker, exists: bool, test_user): file_name = "test_routine.openbb" routine = "do something" current_user = get_current_user() - path = "openbb_terminal.account.account_model" + path = "openbb_terminal.core.session.routines_handler" mocker.patch( target=path + ".get_current_user", @@ -71,7 +71,7 @@ def test_read_routine(mocker, exists: bool, test_user): def test_read_routine_exception(mocker, test_user): file_name = "test_routine.openbb" current_user = get_current_user() - path = "openbb_terminal.account.account_model" + path = "openbb_terminal.core.session.routines_handler" mocker.patch( target=path + ".get_current_user", @@ -104,7 +104,7 @@ def test_save_routine(mocker, exists: bool, test_user): file_name = "test_routine.openbb" routine = "do something" current_user = get_current_user() - path = "openbb_terminal.account.account_model" + path = "openbb_terminal.core.session.routines_handler" mocker.patch( target=path + ".get_current_user", @@ -138,7 +138,7 @@ def test_save_routine(mocker, exists: bool, test_user): def test_save_routine_exception(mocker, test_user): file_name = "test_routine.openbb" routine = "do something" - path = "openbb_terminal.account.account_model" + path = "openbb_terminal.core.session.routines_handler" mocker.patch( target=path + ".get_current_user", From 1af21425aab5b0d0ccf4b9bfaf69f29ed4e43f5d Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Tue, 11 Apr 2023 23:14:59 +0100 Subject: [PATCH 09/22] add space --- openbb_terminal/account/account_controller.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openbb_terminal/account/account_controller.py b/openbb_terminal/account/account_controller.py index defb6b229c4d..9bc5c357c9f3 100644 --- a/openbb_terminal/account/account_controller.py +++ b/openbb_terminal/account/account_controller.py @@ -265,7 +265,7 @@ def call_list(self, other_args: List[str]): display_personal_routines(df, page, pages) else: console.print("[red]No routines found.[/red]") - + console.print("") df = get_default_routines_info(self.DEFAULT_ROUTINES) display_default_routines(df) From 36dee3fbbf3ab021a8780aa76e03952558d4f0df Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 09:54:02 +0100 Subject: [PATCH 10/22] wrap some funcs inside try, except --- openbb_terminal/account/account_view.py | 37 ++++++++++++++----------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/openbb_terminal/account/account_view.py b/openbb_terminal/account/account_view.py index 1f8370b929ae..45f2f93a4e2f 100644 --- a/openbb_terminal/account/account_view.py +++ b/openbb_terminal/account/account_view.py @@ -1,6 +1,7 @@ import pandas as pd from openbb_terminal.helper_funcs import print_rich_table +from openbb_terminal.rich_config import console def display_personal_routines(df: pd.DataFrame, page: int, pages: int): @@ -15,21 +16,23 @@ def display_personal_routines(df: pd.DataFrame, page: int, pages: int): pages : int The total number of pages. """ - title = f"Personal routines - page {page}" - if pages: - title += f" of {pages}" - - if all(c in df.columns for c in ["name", "description", "version", "updated_date"]): - df["updated_date"] = pd.to_datetime(df["updated_date"]) - df["updated_date"] = df["updated_date"].dt.strftime("%Y-%m-%d %H:%M:%S") - df.replace(to_replace=[None], value="-", inplace=True) - print_rich_table( - df=df, - title=title, - headers=["Name", "Description", "Version", "Last update"], - show_index=True, - index_name="#", - ) + try: + title = f"Personal routines - page {page}" + if pages: + title += f" of {pages}" + + df["updated_date"] = pd.to_datetime(df["updated_date"]) + df["updated_date"] = df["updated_date"].dt.strftime("%Y-%m-%d %H:%M:%S") + df.replace(to_replace=[None], value="-", inplace=True) + print_rich_table( + df=df, + title=title, + headers=["Name", "Description", "Version", "Last update"], + show_index=True, + index_name="#", + ) + except Exception: + console.print("Failed to display personal routines.") def display_default_routines(df: pd.DataFrame): @@ -40,7 +43,7 @@ def display_default_routines(df: pd.DataFrame): df : pd.DataFrame The default routines list. """ - if all(c in df.columns for c in ["name", "description", "version", "date_updated"]): + try: df["date_updated"] = pd.to_datetime(df["date_updated"]) df["date_updated"] = df["date_updated"].dt.strftime("%Y-%m-%d %H:%M:%S") df.replace(to_replace=[None], value="-", inplace=True) @@ -51,3 +54,5 @@ def display_default_routines(df: pd.DataFrame): show_index=True, index_name="#", ) + except Exception: + console.print("Failed to display default routines.") From 08cd15733658d8a72528f54e352a78829a362bdf Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 10:11:53 +0100 Subject: [PATCH 11/22] fix account test --- .../account/test_account_controller.py | 22 ++++++++++++++++--- .../test_call_list.txt | 6 +++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/tests/openbb_terminal/account/test_account_controller.py b/tests/openbb_terminal/account/test_account_controller.py index 36b217da63c0..1ad58884737a 100644 --- a/tests/openbb_terminal/account/test_account_controller.py +++ b/tests/openbb_terminal/account/test_account_controller.py @@ -46,9 +46,24 @@ ROUTINES = { "items": [ - {"name": "scrip1", "description": "abc"}, - {"name": "script2", "description": "def"}, - {"name": "script3", "description": "ghi"}, + { + "name": "scrip1", + "description": "abc", + "version": "0.0.0", + "updated_date": "2021-01-01", + }, + { + "name": "script2", + "description": "def", + "version": "0.0.1", + "updated_date": "2022-01-01", + }, + { + "name": "script3", + "description": "ghi", + "version": "0.0.2", + "updated_date": "2023-01-01", + }, ], "total": 3, "page": 1, @@ -75,6 +90,7 @@ def fetch_routines(mocker): path_controller = "openbb_terminal.account.account_controller" mocker.patch( target=f"{path_controller}.AccountController.fetch_default_routines", + return_value=[], ) diff --git a/tests/openbb_terminal/account/txt/test_account_controller/test_call_list.txt b/tests/openbb_terminal/account/txt/test_account_controller/test_call_list.txt index e69de29bb2d1..a702c294c8f5 100644 --- a/tests/openbb_terminal/account/txt/test_account_controller/test_call_list.txt +++ b/tests/openbb_terminal/account/txt/test_account_controller/test_call_list.txt @@ -0,0 +1,6 @@ + name description version updated_date +1 scrip1 abc 0.0.0 2021-01-01 00:00:00 +2 script2 def 0.0.1 2022-01-01 00:00:00 +3 script3 ghi 0.0.2 2023-01-01 00:00:00 + +Failed to display default routines. From daca4a44ff9c028a8268bc9591b81ac8bd419750 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 10:44:10 +0100 Subject: [PATCH 12/22] suppress outputs --- openbb_terminal/core/session/hub_model.py | 41 +++++++++++------- .../core/session/routines_handler.py | 42 ++++++++++++------- openbb_terminal/core/session/session_model.py | 4 +- 3 files changed, 58 insertions(+), 29 deletions(-) diff --git a/openbb_terminal/core/session/hub_model.py b/openbb_terminal/core/session/hub_model.py index d669862859e5..a3a061c6544a 100644 --- a/openbb_terminal/core/session/hub_model.py +++ b/openbb_terminal/core/session/hub_model.py @@ -1,5 +1,5 @@ import json -from typing import Any, Dict, Literal, Optional +from typing import Any, Dict, List, Literal, Optional import requests @@ -301,15 +301,15 @@ def upload_user_field( timeout : int The timeout, by default TIMEOUT silent : bool - Whether to print the status, by default False + Whether to silence the console output, by default False Returns ------- Optional[requests.Response] The response from the put request. """ + console_print = console.print if not silent else lambda *args, **kwargs: None try: - console_print = console.print if not silent else lambda *args, **kwargs: None data: Dict[str, dict] = {key: value} console_print("Sending to OpenBB hub...") @@ -556,11 +556,12 @@ def delete_routine( def list_routines( auth_header: str, - fields: str = "name%2Cdescription%2Cversion%2Cupdated_date", + fields: Optional[List[str]] = None, page: int = 1, size: int = 10, base_url=BASE_URL, timeout: int = TIMEOUT, + silent: bool = False, ) -> Optional[requests.Response]: """List all routines from the server. @@ -568,6 +569,8 @@ def list_routines( ---------- auth_header : str The authorization header, e.g. "Bearer ". + fields : Optional[List[str]] + The fields to return, by default None page : int The page number. size : int @@ -576,61 +579,71 @@ def list_routines( The base url, by default BASE_URL timeout : int The timeout, by default TIMEOUT + silent : bool + Whether to silence the console output, by default False Returns ------- Optional[requests.Response] The response from the get request. """ + console_print = console.print if not silent else lambda *args, **kwargs: None try: + if fields is None: + fields = ["name", "description", "version", "updated_date"] + + fields_str = "%2C".join(fields) response = requests.get( headers={"Authorization": auth_header}, - url=f"{base_url}terminal/script?fields={fields}&page={page}&size={size}", + url=f"{base_url}terminal/script?fields={fields_str}&page={page}&size={size}", timeout=timeout, ) if response.status_code != 200: - console.print("[red]Failed to list your routines.[/red]") + console_print("[red]Failed to list your routines.[/red]") return response except requests.exceptions.ConnectionError: - console.print(f"\n{CONNECTION_ERROR_MSG}") + console_print(f"\n{CONNECTION_ERROR_MSG}") return None except requests.exceptions.Timeout: - console.print(f"\n{CONNECTION_TIMEOUT_MSG}") + console_print(f"\n{CONNECTION_TIMEOUT_MSG}") return None except Exception: - console.print("[red]Failed to list your routines.[/red]") + console_print("[red]Failed to list your routines.[/red]") return None -def get_default_routines(timeout: int = TIMEOUT): +def get_default_routines(timeout: int = TIMEOUT, silent: bool = False): """Get the default routines from CMS. Parameters ---------- timeout : int The timeout, by default TIMEOUT + silent : bool + Whether to silence the console output, by default False Returns ------- Optional[requests.Response] The response from the get request. """ + console_print = console.print if not silent else lambda *args, **kwargs: None try: response = requests.get( url="https://tffo1zc1.directus.app/items/Routines", timeout=timeout, ) if response.status_code != 200: - console.print("[red]Failed to get default routines.[/red]") + console_print("[red]Failed to get default routines.[/red]") return response except requests.exceptions.ConnectionError: - console.print(f"\n{CONNECTION_ERROR_MSG}") + console_print(f"\n{CONNECTION_ERROR_MSG}") return None except requests.exceptions.Timeout: - console.print(f"\n{CONNECTION_TIMEOUT_MSG}") + console_print(f"\n{CONNECTION_TIMEOUT_MSG}") return None except Exception: - console.print("[red]Failed to get default routines.[/red]") + console_print("[red]Failed to get default routines.[/red]") return None diff --git a/openbb_terminal/core/session/routines_handler.py b/openbb_terminal/core/session/routines_handler.py index d6e13627b3e0..0f4f8baf5b4c 100644 --- a/openbb_terminal/core/session/routines_handler.py +++ b/openbb_terminal/core/session/routines_handler.py @@ -10,15 +10,15 @@ from openbb_terminal.rich_config import console -def download_routines( - auth_header: str, -) -> Dict[str, str]: +def download_routines(auth_header: str, silent: bool = True) -> Dict[str, str]: """Download a routine from the server. Parameters ---------- auth_header : str The authorization header, e.g. "Bearer ". + silent : bool + Whether to silence the console output, by default False Returns ------- @@ -27,38 +27,48 @@ def download_routines( """ routines_dict = {} - fields = "name%2Cscript" - response = Hub.list_routines(auth_header, fields=fields, page=1, size=100) + response = Hub.get_default_routines(silent=silent) if response and response.status_code == 200: content = response.json() - items = content.get("items", []) - for routine in items: + data = content.get("data", []) + for routine in data: name = routine.get("name", "") if name: routines_dict[name] = routine.get("script", "") - response = Hub.get_default_routines() + response = Hub.list_routines( + auth_header=auth_header, + fields=["name", "script"], + page=1, + size=100, + silent=silent, + ) if response and response.status_code == 200: content = response.json() - data = content.get("data", []) - for routine in data: + items = content.get("items", []) + for routine in items: name = routine.get("name", "") if name: routines_dict[name] = routine.get("script", "") + return routines_dict -def download_and_save_routines(auth_header: str): +def download_and_save_routines(auth_header: str, silent: bool = True): """Download and save routines. Parameters ---------- auth_header : str The authorization header, e.g. "Bearer ". + silent : bool + Whether to silence the console output, by default False """ - routines = download_routines(auth_header) + routines = download_routines(auth_header=auth_header, silent=silent) for name, content in routines.items(): - save_routine(file_name=f"{name}.openbb", routine=content, force=True) + save_routine( + file_name=f"{name}.openbb", routine=content, force=True, silent=silent + ) def read_routine(file_name: str, folder: Optional[Path] = None) -> Optional[str]: @@ -104,6 +114,7 @@ def save_routine( routine: str, folder: Optional[Path] = None, force: bool = False, + silent: bool = False, ) -> Union[Optional[Path], str]: """Save the routine. @@ -117,12 +128,15 @@ def save_routine( The routines folder. force : bool Force the save. + silent : bool + Whether to silence the console output, by default False Returns ------- Optional[Path, str] The path to the routine or None. """ + console_print = console.print if not silent else lambda *args, **kwargs: None current_user = get_current_user() if folder is None: @@ -140,7 +154,7 @@ def save_routine( f.write(routine) return user_folder / file_name except Exception: - console.print("[red]\nFailed to save routine.[/red]") + console_print("[red]\nFailed to save routine.[/red]") return None diff --git a/openbb_terminal/core/session/session_model.py b/openbb_terminal/core/session/session_model.py index 616cc9176be6..e82ad16c19e2 100644 --- a/openbb_terminal/core/session/session_model.py +++ b/openbb_terminal/core/session/session_model.py @@ -114,7 +114,9 @@ def login(session: dict) -> LoginStatus: "silent": True, }, ) - run_thread(download_and_save_routines, {"auth_header": auth_header}) + run_thread( + download_and_save_routines, {"auth_header": auth_header, "silent": True} + ) Local.apply_configs(configs) Local.update_flair(get_current_user().profile.username) From dc62a4ba848bf22e593eb6b620c218b47f2c9167 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 10:46:16 +0100 Subject: [PATCH 13/22] rewrite docstring --- openbb_terminal/core/session/utils.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/openbb_terminal/core/session/utils.py b/openbb_terminal/core/session/utils.py index 5d4da8601aa6..45ab3e509eef 100644 --- a/openbb_terminal/core/session/utils.py +++ b/openbb_terminal/core/session/utils.py @@ -1,5 +1,5 @@ from threading import Thread -from typing import Any, Type, TypeVar +from typing import Any, Callable, Dict, Type, TypeVar from pydantic import ValidationError @@ -44,15 +44,15 @@ def load_dict_to_model(dictionary: dict, model: Type[T]) -> T: return model() # type: ignore -def run_thread(target, kwargs): - """Run a thread. +def run_thread(target: Callable, kwargs: Dict[str, Any]): + """Run a daemon thread, with the given target and keyword arguments. Parameters ---------- - target : function + target : Callable The target function. - args : tuple - The arguments. + kwargs : Dict[str, Any] + The keyword arguments. """ thread = Thread(target=target, kwargs=kwargs, daemon=True) thread.start() From 977a98ccfa8f708133e88382d34c94dd203c8fe9 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 11:05:56 +0100 Subject: [PATCH 14/22] remove circular import --- .../core/session/routines_handler.py | 19 +----- openbb_terminal/core/session/session_model.py | 63 +++++++++++++++---- 2 files changed, 51 insertions(+), 31 deletions(-) diff --git a/openbb_terminal/core/session/routines_handler.py b/openbb_terminal/core/session/routines_handler.py index 0f4f8baf5b4c..c57666b91633 100644 --- a/openbb_terminal/core/session/routines_handler.py +++ b/openbb_terminal/core/session/routines_handler.py @@ -10,7 +10,7 @@ from openbb_terminal.rich_config import console -def download_routines(auth_header: str, silent: bool = True) -> Dict[str, str]: +def download_routines(auth_header: str, silent: bool = False) -> Dict[str, str]: """Download a routine from the server. Parameters @@ -54,23 +54,6 @@ def download_routines(auth_header: str, silent: bool = True) -> Dict[str, str]: return routines_dict -def download_and_save_routines(auth_header: str, silent: bool = True): - """Download and save routines. - - Parameters - ---------- - auth_header : str - The authorization header, e.g. "Bearer ". - silent : bool - Whether to silence the console output, by default False - """ - routines = download_routines(auth_header=auth_header, silent=silent) - for name, content in routines.items(): - save_routine( - file_name=f"{name}.openbb", routine=content, force=True, silent=silent - ) - - def read_routine(file_name: str, folder: Optional[Path] = None) -> Optional[str]: """Read the routine. diff --git a/openbb_terminal/core/session/session_model.py b/openbb_terminal/core/session/session_model.py index e82ad16c19e2..ab26f0186800 100644 --- a/openbb_terminal/core/session/session_model.py +++ b/openbb_terminal/core/session/session_model.py @@ -21,7 +21,10 @@ set_current_user, set_default_user, ) -from openbb_terminal.core.session.routines_handler import download_and_save_routines +from openbb_terminal.core.session.routines_handler import ( + download_routines, + save_routine, +) from openbb_terminal.core.session.sources_handler import get_updated_hub_sources from openbb_terminal.core.session.utils import run_thread from openbb_terminal.helper_funcs import system_clear @@ -103,20 +106,10 @@ def login(session: dict) -> LoginStatus: set_current_user(hub_user) auth_header = hub_user.profile.get_auth_header() - updated_sources = get_updated_hub_sources(configs) - if updated_sources: - run_thread( - Hub.upload_user_field, - { - "key": "features_sources", - "value": updated_sources, - "auth_header": auth_header, - "silent": True, - }, - ) run_thread( - download_and_save_routines, {"auth_header": auth_header, "silent": True} + update_backend_sources, {"auth_header": auth_header, "configs": configs} ) + run_thread(download_and_save_routines, {"auth_header": auth_header}) Local.apply_configs(configs) Local.update_flair(get_current_user().profile.username) @@ -128,6 +121,50 @@ def login(session: dict) -> LoginStatus: return LoginStatus.NO_RESPONSE +def update_backend_sources(auth_header, configs, silent: bool = True): + """Update backend sources if new source or command path available. + + Parameters + ---------- + auth_header : str + The authorization header, e.g. "Bearer ". + configs : Dict + Dictionary with configs + silent : bool + Whether to silence the console output, by default True + """ + console_print = console.print if not silent else lambda *args, **kwargs: None + + try: + updated_sources = get_updated_hub_sources(configs) + if updated_sources: + Hub.upload_user_field( + key="features_sources", + value=updated_sources, + auth_header=auth_header, + silent=silent, + ) + except Exception: + console_print("[red]Failed to update backend sources.[/red]") + + +def download_and_save_routines(auth_header: str, silent: bool = True): + """Download and save routines. + + Parameters + ---------- + auth_header : str + The authorization header, e.g. "Bearer ". + silent : bool + Whether to silence the console output, by default True + """ + routines = download_routines(auth_header=auth_header, silent=silent) + for name, content in routines.items(): + save_routine( + file_name=f"{name}.openbb", routine=content, force=True, silent=silent + ) + + def logout( auth_header: Optional[str] = None, token: Optional[str] = None, From db357d85817e3fd048b2f872e60d7829d38305da Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 11:06:59 +0100 Subject: [PATCH 15/22] reverse order --- openbb_terminal/core/session/session_model.py | 37 +++++++++---------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/openbb_terminal/core/session/session_model.py b/openbb_terminal/core/session/session_model.py index ab26f0186800..1bfd4710f0be 100644 --- a/openbb_terminal/core/session/session_model.py +++ b/openbb_terminal/core/session/session_model.py @@ -106,11 +106,10 @@ def login(session: dict) -> LoginStatus: set_current_user(hub_user) auth_header = hub_user.profile.get_auth_header() + run_thread(download_and_save_routines, {"auth_header": auth_header}) run_thread( update_backend_sources, {"auth_header": auth_header, "configs": configs} ) - run_thread(download_and_save_routines, {"auth_header": auth_header}) - Local.apply_configs(configs) Local.update_flair(get_current_user().profile.username) @@ -121,6 +120,23 @@ def login(session: dict) -> LoginStatus: return LoginStatus.NO_RESPONSE +def download_and_save_routines(auth_header: str, silent: bool = True): + """Download and save routines. + + Parameters + ---------- + auth_header : str + The authorization header, e.g. "Bearer ". + silent : bool + Whether to silence the console output, by default True + """ + routines = download_routines(auth_header=auth_header, silent=silent) + for name, content in routines.items(): + save_routine( + file_name=f"{name}.openbb", routine=content, force=True, silent=silent + ) + + def update_backend_sources(auth_header, configs, silent: bool = True): """Update backend sources if new source or command path available. @@ -148,23 +164,6 @@ def update_backend_sources(auth_header, configs, silent: bool = True): console_print("[red]Failed to update backend sources.[/red]") -def download_and_save_routines(auth_header: str, silent: bool = True): - """Download and save routines. - - Parameters - ---------- - auth_header : str - The authorization header, e.g. "Bearer ". - silent : bool - Whether to silence the console output, by default True - """ - routines = download_routines(auth_header=auth_header, silent=silent) - for name, content in routines.items(): - save_routine( - file_name=f"{name}.openbb", routine=content, force=True, silent=silent - ) - - def logout( auth_header: Optional[str] = None, token: Optional[str] = None, From c08f9d6292693dbb4b7b741944bd519221422516 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 11:26:59 +0100 Subject: [PATCH 16/22] update docstring --- openbb_terminal/core/session/routines_handler.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/openbb_terminal/core/session/routines_handler.py b/openbb_terminal/core/session/routines_handler.py index c57666b91633..75cb726ff401 100644 --- a/openbb_terminal/core/session/routines_handler.py +++ b/openbb_terminal/core/session/routines_handler.py @@ -11,7 +11,7 @@ def download_routines(auth_header: str, silent: bool = False) -> Dict[str, str]: - """Download a routine from the server. + """Download default and personal routines. Parameters ---------- @@ -36,6 +36,7 @@ def download_routines(auth_header: str, silent: bool = False) -> Dict[str, str]: if name: routines_dict[name] = routine.get("script", "") + # Number of routines downloaded is limited to 100 response = Hub.list_routines( auth_header=auth_header, fields=["name", "script"], From e93addf3c6d99220e4f9b5126e762ed20eb2611c Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 12:31:49 +0100 Subject: [PATCH 17/22] allow exe with spaces in file name --- openbb_terminal/terminal_controller.py | 66 ++++++++++---------------- 1 file changed, 25 insertions(+), 41 deletions(-) diff --git a/openbb_terminal/terminal_controller.py b/openbb_terminal/terminal_controller.py index 498ff09d83f1..09150c3cae73 100644 --- a/openbb_terminal/terminal_controller.py +++ b/openbb_terminal/terminal_controller.py @@ -261,13 +261,13 @@ def call_guess(self, other_args: List[str]) -> None: current_user = get_current_user() if self.GUESS_NUMBER_TRIES_LEFT == 0 and self.GUESS_SUM_SCORE < 0.01: - parser_exe = argparse.ArgumentParser( + parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="guess", description="Guess command to achieve task successfully.", ) - parser_exe.add_argument( + parser.add_argument( "-l", "--limit", type=check_positive, @@ -277,7 +277,7 @@ def call_guess(self, other_args: List[str]) -> None: ) if other_args and "-" not in other_args[0][0]: other_args.insert(0, "-l") - ns_parser_guess = self.parse_simple_args(parser_exe, other_args) + ns_parser_guess = self.parse_simple_args(parser, other_args) if self.GUESS_TOTAL_TRIES == 0: self.GUESS_NUMBER_TRIES_LEFT = ns_parser_guess.limit @@ -525,26 +525,7 @@ def call_exe(self, other_args: List[str]): "type `about exe`.\n[/red]" ) return - - full_input = " ".join(other_args) - other_args_processed = ( - full_input.split(" ") if " " in full_input else [full_input] - ) - self.queue = [] - - path_routine = "" - args = list() - for idx, path_dir in enumerate(other_args_processed): - if path_dir in ("-i", "--input"): - args = [path_routine[1:]] + other_args_processed[idx:] - break - if path_dir not in ("--file"): - path_routine += f"/{path_dir}" - - if not args: - args = [path_routine[1:]] - - parser_exe = argparse.ArgumentParser( + parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="exe", @@ -552,20 +533,25 @@ def call_exe(self, other_args: List[str]): "`exe --example` and for documentation and to learn how create your own script " "type `about exe`.", ) - parser_exe.add_argument( + parser.add_argument( "--file", help="The path or .openbb file to run.", - dest="path", - default=None, + dest="file", + required="-h" not in other_args + and "--help" not in other_args + and "-e" not in other_args + and "--example" not in other_args, + type=str, + nargs="+", ) - parser_exe.add_argument( + parser.add_argument( "-i", "--input", help="Select multiple inputs to be replaced in the routine and separated by commas. E.g. GME,AMC,BTC-USD", dest="routine_args", type=lambda s: [str(item) for item in s.split(",")], ) - parser_exe.add_argument( + parser.add_argument( "-e", "--example", help="Run an example script to understand how routines can be used.", @@ -573,25 +559,23 @@ def call_exe(self, other_args: List[str]): action="store_true", default=False, ) + if other_args and "-" not in other_args[0][0]: + other_args.insert(0, "--file") + ns_parser = self.parse_known_args_and_warn(parser, other_args) - if not args[0]: - return console.print("[red]Please select an .openbb routine file.[/red]\n") - - if args and "-" not in args[0][0]: - args.insert(0, "--file") - ns_parser_exe = self.parse_simple_args(parser_exe, args) - if ns_parser_exe and (ns_parser_exe.path or ns_parser_exe.example): - if ns_parser_exe.example: + if ns_parser: + if ns_parser.example: path = MISCELLANEOUS_DIRECTORY / "routines" / "routine_example.openbb" console.print( "[green]Executing an example, please type `about exe` " "to learn how to create your own script.[/green]\n" ) time.sleep(3) - elif ns_parser_exe.path in self.ROUTINE_CHOICES["--file"]: - path = self.ROUTINE_FILES[ns_parser_exe.path] + elif ns_parser.file: + file_path = " ".join(ns_parser.file) + path = self.ROUTINE_FILES.get(file_path, Path(file_path)) else: - path = ns_parser_exe.path + return with open(path) as fp: raw_lines = [ @@ -610,8 +594,8 @@ def call_exe(self, other_args: List[str]): # Check if dynamic parameter exists in script if "$ARGV" in rawline: # Check if user has provided inputs through -i or --input - if ns_parser_exe.routine_args: - for i, arg in enumerate(ns_parser_exe.routine_args): + if ns_parser.routine_args: + for i, arg in enumerate(ns_parser.routine_args): # Check what is the location of the ARGV to be replaced if f"$ARGV[{i}]" in templine: templine = templine.replace(f"$ARGV[{i}]", arg) From fdbf5c514c0c0f94a32b5206a2e3eeb3a245ac01 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 12:37:14 +0100 Subject: [PATCH 18/22] fix exe with input --- openbb_terminal/terminal_controller.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openbb_terminal/terminal_controller.py b/openbb_terminal/terminal_controller.py index 09150c3cae73..6ebac94a2c88 100644 --- a/openbb_terminal/terminal_controller.py +++ b/openbb_terminal/terminal_controller.py @@ -520,9 +520,9 @@ def call_exe(self, other_args: List[str]): if not other_args: console.print( - "[red]Provide a path to the routine you wish to execute. For an example, please use " + "[info]Provide a path to the routine you wish to execute. For an example, please use " "`exe --example` and for documentation and to learn how create your own script " - "type `about exe`.\n[/red]" + "type `about exe`.\n[/info]" ) return parser = argparse.ArgumentParser( From 16c011b8cbb97de48a013edd903c17e53ef8335a Mon Sep 17 00:00:00 2001 From: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Date: Wed, 12 Apr 2023 12:38:44 +0100 Subject: [PATCH 19/22] Update terminal_controller.py --- openbb_terminal/terminal_controller.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openbb_terminal/terminal_controller.py b/openbb_terminal/terminal_controller.py index 6ebac94a2c88..d3ddd4fefb01 100644 --- a/openbb_terminal/terminal_controller.py +++ b/openbb_terminal/terminal_controller.py @@ -567,8 +567,8 @@ def call_exe(self, other_args: List[str]): if ns_parser.example: path = MISCELLANEOUS_DIRECTORY / "routines" / "routine_example.openbb" console.print( - "[green]Executing an example, please type `about exe` " - "to learn how to create your own script.[/green]\n" + "[info]Executing an example, please type `about exe` " + "to learn how to create your own script.[/info]\n" ) time.sleep(3) elif ns_parser.file: From a465bae63b739148dd32e2d0aaf995b309b36124 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 15:20:34 +0100 Subject: [PATCH 20/22] fix regex for file extensions --- openbb_terminal/helper_funcs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openbb_terminal/helper_funcs.py b/openbb_terminal/helper_funcs.py index 33c1a64cb5ca..299f822e865b 100644 --- a/openbb_terminal/helper_funcs.py +++ b/openbb_terminal/helper_funcs.py @@ -170,7 +170,7 @@ def parse_and_split_input(an_input: str, custom_filters: List) -> List[str]: # everything from ` -f ` to the next known extension file_flag = r"(\ -f |\ --file )" up_to = r".*?" - known_extensions = r"(\.xlsx|.csv|.xls|.tsv|.json|.yaml|.ini|.openbb|.ipynb)" + known_extensions = r"(\.(xlsx|csv|xls|tsv|json|yaml|ini|openbb|ipynb))" unix_path_arg_exp = f"({file_flag}{up_to}{known_extensions})" # Add custom expressions to handle edge cases of individual controllers From 74238ecd7211c9b26c63290d22449d0ac7103c23 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 15:43:46 +0100 Subject: [PATCH 21/22] pylint --- openbb_terminal/core/session/session_controller.py | 1 + 1 file changed, 1 insertion(+) diff --git a/openbb_terminal/core/session/session_controller.py b/openbb_terminal/core/session/session_controller.py index 8d3ccd1d5fa2..51d76d174b9f 100644 --- a/openbb_terminal/core/session/session_controller.py +++ b/openbb_terminal/core/session/session_controller.py @@ -76,6 +76,7 @@ def prompt(welcome=True): def launch_terminal(): """Launch terminal""" + # pylint: disable=import-outside-toplevel from openbb_terminal import terminal_controller terminal_controller.parse_args_and_run() From 399db994679994e4565a6161d9eea0c6991e8823 Mon Sep 17 00:00:00 2001 From: Diogo Sousa Date: Wed, 12 Apr 2023 18:57:55 +0100 Subject: [PATCH 22/22] put default routines url inside constants --- openbb_terminal/core/session/constants.py | 3 ++- openbb_terminal/core/session/hub_model.py | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/openbb_terminal/core/session/constants.py b/openbb_terminal/core/session/constants.py index ca6ff820ede0..98cc295bcf49 100644 --- a/openbb_terminal/core/session/constants.py +++ b/openbb_terminal/core/session/constants.py @@ -8,7 +8,8 @@ COLORS_URL = HUB_URL + "app/terminal/theme" CHARTS_TABLES_URL = HUB_URL + "app/terminal/theme/charts-tables" -TIMEOUT = 15 +DEFAULT_ROUTINES_URL = "https://tffo1zc1.directus.app/items/Routines" +TIMEOUT = 15 CONNECTION_ERROR_MSG = "[red]Connection error.[/red]" CONNECTION_TIMEOUT_MSG = "[red]Connection timeout.[/red]" diff --git a/openbb_terminal/core/session/hub_model.py b/openbb_terminal/core/session/hub_model.py index a3a061c6544a..622094170d2e 100644 --- a/openbb_terminal/core/session/hub_model.py +++ b/openbb_terminal/core/session/hub_model.py @@ -7,6 +7,7 @@ BASE_URL, CONNECTION_ERROR_MSG, CONNECTION_TIMEOUT_MSG, + DEFAULT_ROUTINES_URL, TIMEOUT, ) from openbb_terminal.core.session.current_system import get_current_system @@ -612,7 +613,9 @@ def list_routines( return None -def get_default_routines(timeout: int = TIMEOUT, silent: bool = False): +def get_default_routines( + url: str = DEFAULT_ROUTINES_URL, timeout: int = TIMEOUT, silent: bool = False +): """Get the default routines from CMS. Parameters @@ -630,7 +633,7 @@ def get_default_routines(timeout: int = TIMEOUT, silent: bool = False): console_print = console.print if not silent else lambda *args, **kwargs: None try: response = requests.get( - url="https://tffo1zc1.directus.app/items/Routines", + url=url, timeout=timeout, ) if response.status_code != 200: