Creates a "--dev" flag that points to dev backend for testing with hub (#5319)

* check that routine title is valid

* more updates

* small fixes

* override local routine

* more improvements to routine logic

* --debug runs .dev

* few more updates

* small fix

* rename BASE_URL from ultima to ULTIMA_BASE_URL

* use debug from dataclasses instead of env since env doesn't get updated

* create --dev flag that can point to .dev backend

* merge conflits

* few changes, made it actually work 🤣

---------

Co-authored-by: tehcoderer <me@tehcoderer.com>
This commit is contained in:
DidierRLopes
2023-08-14 01:20:07 -05:00
committed by GitHub
parent 3e48648487
commit c40c3f7529
19 changed files with 157 additions and 99 deletions

View File

@@ -255,6 +255,7 @@ class AccountController(BaseController):
auth_header=get_current_user().profile.get_auth_header(),
page=ns_parser.page,
size=ns_parser.size,
base_url=Hub.BackendEnvironment.BASE_URL,
)
df, page, pages = get_personal_routines_info(response)
if not df.empty:
@@ -356,6 +357,7 @@ class AccountController(BaseController):
"routine": routine,
"tags": tags,
"public": ns_parser.public,
"base_url": Hub.BackendEnvironment.BASE_URL,
}
response = Hub.upload_routine(**kwargs) # type: ignore
@@ -412,6 +414,7 @@ class AccountController(BaseController):
response = Hub.download_routine(
auth_header=get_current_user().profile.get_auth_header(),
uuid=self.REMOTE_CHOICES[name],
base_url=Hub.BackendEnvironment.BASE_URL
)
if response and response.status_code == 200:
data = [response.json(), "personal"]
@@ -499,6 +502,7 @@ class AccountController(BaseController):
response = Hub.delete_routine(
auth_header=get_current_user().profile.get_auth_header(),
uuid=self.REMOTE_CHOICES[name],
base_url=Hub.BackendEnvironment.BASE_URL
)
if (
response
@@ -551,6 +555,7 @@ class AccountController(BaseController):
response = Hub.generate_personal_access_token(
auth_header=get_current_user().profile.get_auth_header(),
base_url=Hub.BackendEnvironment.BASE_URL,
days=ns_parser.days,
)
if response and response.status_code == 200:

View File

@@ -18,7 +18,7 @@ from openbb_terminal.rich_config import console
logger = logging.getLogger(__name__)
BASE_URL = "https://api.ultimainsights.ai/v1"
ULTIMA_BASE_URL = "https://api.ultimainsights.ai/v1"
NO_API_KEY = "REPLACE_ME"
@@ -69,10 +69,10 @@ def get_news(term: str = "", sort: str = "articlePublishedDate") -> pd.DataFrame
if term in supported_terms():
if auth_header:
data = request(
f"{BASE_URL}/getNewsArticles/{term}", headers=auth_header
f"{ULTIMA_BASE_URL}/getNewsArticles/{term}", headers=auth_header
)
else:
data = request(f"{BASE_URL}/getNewsArticles/{term}")
data = request(f"{ULTIMA_BASE_URL}/getNewsArticles/{term}")
else:
console.print(
"[red]Ticker not supported. Unable to retrieve data\n[/red]"
@@ -150,7 +150,7 @@ def supported_terms() -> list:
# https://stackoverflow.com/questions/27835619/urllib-and-ssl-certificate-verify-failed-error/73270162#73270162
os.environ["REQUESTS_CA_BUNDLE"] = certifi.where()
os.environ["SSL_CERT_FILE"] = certifi.where()
data = request(f"{BASE_URL}/supportedTickers")
data = request(f"{ULTIMA_BASE_URL}/supportedTickers")
return list(data.json())
@@ -176,7 +176,7 @@ def get_company_info(ticker: str) -> dict:
os.environ["SSL_CERT_FILE"] = certifi.where()
if ticker in supported_terms():
data = request(f"{BASE_URL}/getCompanyInfo/{ticker}")
data = request(f"{ULTIMA_BASE_URL}/getCompanyInfo/{ticker}")
return data.json()
console.print("[red]Ticker not supported. Unable to retrieve data\n[/red]")
return {}
@@ -213,9 +213,9 @@ def get_top_headlines(ticker: str) -> dict:
if ticker in supported_terms():
if auth_header:
data = request(f"{BASE_URL}/getTopHeadlines/{ticker}", headers=auth_header)
data = request(f"{ULTIMA_BASE_URL}/getTopHeadlines/{ticker}", headers=auth_header)
else:
data = request(f"{BASE_URL}/getTopHeadlines/{ticker}")
data = request(f"{ULTIMA_BASE_URL}/getTopHeadlines/{ticker}")
if (
hasattr(data, "status") and data.status_code == 429
): # If data request failed

View File

@@ -8,6 +8,7 @@ from unittest.mock import patch
from openbb_terminal.helper_funcs import check_file_type_saved, check_positive
from openbb_terminal.rich_config import get_ordered_list_sources
from openbb_terminal.core.session.current_system import get_current_system
def __mock_parse_known_args_and_warn(
@@ -211,7 +212,7 @@ def __patch_controller_functions(controller):
),
]
if str(environ.get("DEBUG_MODE", "false")).lower() != "true":
if not get_current_system().DEBUG_MODE:
rich.start()
patched_function_list = []
for patcher in patcher_list:
@@ -219,7 +220,7 @@ def __patch_controller_functions(controller):
yield patched_function_list
if str(environ.get("DEBUG_MODE", "false")).lower() != "true":
if not get_current_system().DEBUG_MODE:
rich.stop()
for patcher in patcher_list:
patcher.stop()
@@ -317,7 +318,7 @@ def build_controller_choice_map(controller) -> dict:
argument_parser=argument_parser
)
except Exception as exception:
if str(environ.get("DEBUG_MODE", "false")).lower() == "true":
if get_current_system().DEBUG_MODE:
raise Exception(
f"On command : `{command}`.\n{str(exception)}"
) from exception

View File

@@ -54,6 +54,7 @@ class SystemModel(BaseModel):
# Others
TEST_MODE: bool = False
DEBUG_MODE: bool = False
DEV_BACKEND: bool = False
ENABLE_AUTHENTICATION: bool = True
HEADLESS: bool = False

View File

@@ -17,6 +17,8 @@ import plotly.graph_objects as go
from packaging import version
from reportlab.graphics import renderPDF
from openbb_terminal.core.session.constants import BackendEnvironment
# pylint: disable=C0415
try:
from pywry import PyWry
@@ -441,10 +443,7 @@ class Backend(PyWry):
self.check_backend()
endpoint = {True: "login", False: "logout"}[login]
if str(os.environ.get("DEBUG_MODE", "false")).lower() == "true":
json_url = f"https://my.openbb.dev/{endpoint}?pywry=true"
else:
json_url = f"https://my.openbb.co/{endpoint}?pywry=true"
json_url = f"{BackendEnvironment.HUB_URL}{endpoint}?pywry=true"
outgoing = dict(
json_data=dict(url=json_url),

View File

@@ -1,20 +1,16 @@
from os import environ
if str(environ.get("DEBUG_MODE", "false")).lower() == "true":
BASE_URL = "https://payments.openbb.dev/"
HUB_URL = "https://my.openbb.dev/"
else:
class HubEnvironment:
# BASE_URL = "http://127.0.0.1:8000/"
BASE_URL = "https://payments.openbb.co/"
HUB_URL = "https://my.openbb.co/"
# BASE_URL = "http://127.0.0.1:8000/"
def __new__(cls, *args, **kwargs): # pylint: disable=W0613
"""Create a singleton instance of the backend."""
if not hasattr(cls, "instance"):
cls.instance = super().__new__(cls) # pylint: disable=E1120
return cls.instance
REGISTER_URL = HUB_URL + "register"
SUPPORT_URL = HUB_URL + "app/terminal/support"
SOURCES_URL = HUB_URL + "app/terminal/data-sources"
KEYS_URL = HUB_URL + "app/terminal/api-keys"
COLORS_URL = HUB_URL + "app/terminal/theme"
CHARTS_TABLES_URL = HUB_URL + "app/terminal/theme/charts-tables"
BackendEnvironment = HubEnvironment()
DEFAULT_ROUTINES_URL = "https://openbb-cms.directus.app/items/Routines"

View File

@@ -2,16 +2,16 @@ import datetime
import json
from typing import Any, Dict, List, Literal, Optional
from uuid import UUID
from os import environ
import requests
from jose import jwt
from openbb_terminal.core.session.constants import (
BASE_URL,
CONNECTION_ERROR_MSG,
CONNECTION_TIMEOUT_MSG,
DEFAULT_ROUTINES_URL,
TIMEOUT,
BackendEnvironment,
)
from openbb_terminal.core.session.current_system import get_current_system
from openbb_terminal.core.session.current_user import get_current_user
@@ -19,7 +19,10 @@ from openbb_terminal.rich_config import console
def create_session(
email: str, password: str, base_url: str = BASE_URL, timeout: int = TIMEOUT
email: str,
password: str,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
) -> Optional[requests.Response]:
"""Create a session.
@@ -72,7 +75,7 @@ def check_token_expiration(token: str):
def create_session_from_token(
token: str, base_url: str = BASE_URL, timeout: int = TIMEOUT
token: str, base_url: str = BackendEnvironment.BASE_URL, timeout: int = TIMEOUT
):
"""Create a session from token.
@@ -109,7 +112,10 @@ def create_session_from_token(
def delete_session(
auth_header: str, token: str, base_url: str = BASE_URL, timeout: int = TIMEOUT
auth_header: str,
token: str,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
) -> Optional[requests.Response]:
"""Delete the session.
@@ -191,7 +197,7 @@ def get_session(email: str, password: str) -> dict:
dict
The session info.
"""
response = create_session(email, password)
response = create_session(email, password, base_url=BackendEnvironment.BASE_URL)
if response is None:
return {}
return process_session_response(response)
@@ -210,14 +216,14 @@ def get_session_from_token(token: str) -> dict:
dict
The session info.
"""
response = create_session_from_token(token)
response = create_session_from_token(token, base_url=BackendEnvironment.BASE_URL)
if response is None:
return {}
return process_session_response(response)
def fetch_user_configs(
session: dict, base_url: str = BASE_URL, timeout: int = TIMEOUT
session: dict, base_url: str = BackendEnvironment.BASE_URL, timeout: int = TIMEOUT
) -> Optional[requests.Response]:
"""Fetch user configurations.
@@ -259,7 +265,10 @@ def fetch_user_configs(
def clear_user_configs(
config: str, auth_header: str, base_url: str = BASE_URL, timeout: int = TIMEOUT
config: str,
auth_header: str,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
) -> Optional[requests.Response]:
"""Clear user configurations to the server.
@@ -308,7 +317,7 @@ def upload_user_field(
key: str,
value: Any,
auth_header: str,
base_url: str = BASE_URL,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
silent: bool = False,
) -> Optional[requests.Response]:
@@ -366,7 +375,7 @@ def upload_config(
value: str,
type_: Literal["settings", "terminal_style"],
auth_header: str,
base_url: str = BASE_URL,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
) -> Optional[requests.Response]:
"""Patch user configurations to the server.
@@ -430,7 +439,7 @@ def upload_routine(
override: bool = False,
tags: str = "",
public: bool = False,
base_url: str = BASE_URL,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
) -> Optional[requests.Response]:
"""Send a routine to the server.
@@ -468,7 +477,6 @@ def upload_routine(
"version": get_current_system().VERSION,
"public": public,
}
try:
response = requests.post(
headers={"Authorization": auth_header},
@@ -478,17 +486,20 @@ def upload_routine(
)
if response.status_code == 200:
username = get_current_user().profile.username
console.print("[green]Successfully uploaded your routine.[/green]")
console.print("[green]Successfully uploaded your routine.[/]")
run_env = BackendEnvironment.HUB_URL.rstrip("/")
if str(environ.get("DEBUG_MODE", "false")).lower() == "true":
run_env = "dev"
else:
run_env = "co"
if public:
console.print(f"\n[yellow]Share or edit it at https://my.openbb.{run_env}/u/{username}/routine/{name.replace(' ', '-')}[/yellow]")
console.print(
f"\n[yellow]Share or edit it at {run_env}/u/{username}/routine/{name.replace(' ', '-')}[/]"
)
else:
console.print(f"\n[yellow]Edit it at https://my.openbb.{run_env}/u/{username}/routine/{name.replace(' ', '-')}[/yellow]")
console.print(f"\n[yellow]Go to {run_env} to edit this script,[/]")
console.print(
f"[yellow]or even make it public so you can access it at "
f"{run_env}/u/{username}/routine/{name.replace(' ', '-')}[/]"
)
elif response.status_code != 409: # 409: routine already exists
console.print(
"[red]" + response.json().get("detail", "Unknown error.") + "[/red]"
@@ -508,7 +519,7 @@ def upload_routine(
def download_routine(
auth_header: str,
uuid: UUID,
base_url=BASE_URL,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
) -> Optional[requests.Response]:
"""Download a routine from the server.
@@ -554,7 +565,7 @@ def download_routine(
def delete_routine(
auth_header: str,
uuid: UUID,
base_url=BASE_URL,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
) -> Optional[requests.Response]:
"""Delete a routine from the server.
@@ -604,7 +615,7 @@ def list_routines(
fields: Optional[List[str]] = None,
page: int = 1,
size: int = 10,
base_url=BASE_URL,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
silent: bool = False,
) -> Optional[requests.Response]:
@@ -695,7 +706,10 @@ def get_default_routines(
def generate_personal_access_token(
auth_header: str, base_url: str = BASE_URL, timeout: int = TIMEOUT, days: int = 30
auth_header: str,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
days: int = 30,
) -> Optional[requests.Response]:
"""
Generate an OpenBB Personal Access Token.
@@ -744,7 +758,9 @@ def generate_personal_access_token(
def get_personal_access_token(
auth_header: str, base_url: str = BASE_URL, timeout: int = TIMEOUT
auth_header: str,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
) -> Optional[requests.Response]:
"""
Show the user's OpenBB Personal Access Token.
@@ -789,7 +805,9 @@ def get_personal_access_token(
def revoke_personal_access_token(
auth_header: str, base_url: str = BASE_URL, timeout: int = TIMEOUT
auth_header: str,
base_url: str = BackendEnvironment.BASE_URL,
timeout: int = TIMEOUT,
) -> Optional[requests.Response]:
"""
Delete the user's OpenBB Personal Access Token.

View File

@@ -51,6 +51,7 @@ def download_routines(auth_header: str, silent: bool = False) -> list:
fields=["name", "script"],
page=1,
size=100,
base_url=Hub.BackendEnvironment.BASE_URL,
silent=silent,
)
if response and response.status_code == 200:

View File

@@ -5,11 +5,11 @@ from prompt_toolkit import PromptSession
import openbb_terminal.core.session.local_model as Local
from openbb_terminal.core.config.paths import PACKAGE_DIRECTORY
from openbb_terminal.core.plots.backend import plots_backend
from openbb_terminal.core.session.constants import (
REGISTER_URL,
SUPPORT_URL,
from openbb_terminal.core.session.constants import BackendEnvironment
from openbb_terminal.core.session.current_system import (
get_current_system,
set_system_variable,
)
from openbb_terminal.core.session.current_system import get_current_system
from openbb_terminal.core.session.session_model import (
LoginStatus,
create_session,
@@ -24,8 +24,12 @@ def display_welcome_message(links: bool = True) -> None:
with open(PACKAGE_DIRECTORY / "core" / "session" / "banner.txt") as f:
console.print(f"[menu]{f.read()}[/menu]\n")
if links:
console.print(f"Register : [cmds]{REGISTER_URL}[/cmds]")
console.print(f"Support : [cmds]{SUPPORT_URL}[/cmds]")
console.print(
f"Register : [cmds]{BackendEnvironment.HUB_URL + 'register'}[/cmds]"
)
console.print(
f"Support : [cmds]{BackendEnvironment.HUB_URL + 'app/terminal/support'}[/cmds]"
)
def get_user_input() -> Tuple[str, str, bool]:
@@ -135,13 +139,15 @@ def prompt_cli(welcome: bool = True):
# pylint: disable=inconsistent-return-statements
def launch_terminal(debug: bool = False, queue: Optional[List[str]] = None):
def launch_terminal(
debug: bool = False, dev: bool = False, queue: Optional[List[str]] = None
):
"""Launch terminal"""
# pylint: disable=import-outside-toplevel
from openbb_terminal import terminal_controller
if queue:
return terminal_controller.main(debug, queue, module="")
return terminal_controller.main(debug, dev, queue, module="")
terminal_controller.parse_args_and_run()
@@ -170,8 +176,13 @@ def main(
welcome: bool = True,
prompt: bool = True,
queue: Optional[List[str]] = None,
dev: bool = False,
):
"""Main function"""
if dev:
set_system_variable("DEV_BACKEND", True)
BackendEnvironment.BASE_URL = "https://payments.openbb.dev/"
BackendEnvironment.HUB_URL = "https://my.openbb.dev/"
local_session = Local.get_session() if session is None else session

View File

@@ -93,7 +93,7 @@ def login(session: Dict, remember: bool = False) -> LoginStatus:
preferences=get_current_user().preferences,
sources=SourcesModel(),
)
response = Hub.fetch_user_configs(session)
response = Hub.fetch_user_configs(session, Hub.BackendEnvironment.BASE_URL)
if response is not None:
if response.status_code == 200:
configs = json.loads(response.content)
@@ -159,6 +159,7 @@ def update_backend_sources(auth_header, configs, silent: bool = True):
key="features_sources",
value=updated_sources,
auth_header=auth_header,
base_url=Hub.BackendEnvironment.BASE_URL,
silent=silent,
)
except Exception:
@@ -190,7 +191,7 @@ def logout(
success = True
r = Hub.delete_session(auth_header, token)
r = Hub.delete_session(auth_header, token, base_url=Hub.BackendEnvironment.BASE_URL)
if not r or r.status_code != 200:
success = False

View File

@@ -8,7 +8,7 @@ import logging
from typing import Callable, Dict, List, Optional
from openbb_terminal import keys_model, keys_view
from openbb_terminal.core.session.constants import KEYS_URL
from openbb_terminal.core.session.constants import BackendEnvironment
from openbb_terminal.core.session.current_user import get_current_user, is_local
from openbb_terminal.core.session.env_handler import get_reading_order
from openbb_terminal.custom_prompt_toolkit import NestedCompleter
@@ -75,7 +75,7 @@ class KeysController(BaseController): # pylint: disable=too-many-public-methods
"""
reading_order = get_reading_order()
hierarchy = "\n ".join(list(map(str, reversed(reading_order))))
return hierarchy if is_local() else f"{KEYS_URL}\n {hierarchy}"
return hierarchy if is_local() else f"{BackendEnvironment.HUB_URL + 'app/terminal/api-keys'}\n {hierarchy}"
def print_help(self, update_status: bool = True, reevaluate: bool = True):
"""Print help"""

View File

@@ -1091,6 +1091,7 @@ class BaseController(metaclass=ABCMeta):
"routine": routine,
"tags": SESSION_RECORDED_TAGS,
"public": SESSION_RECORDED_PUBLIC,
"base_url": Hub.BackendEnvironment.BASE_URL,
}
response = Hub.upload_routine(**kwargs) # type: ignore
if response is not None and response.status_code == 409:

View File

@@ -21,6 +21,7 @@ from openbb_terminal.portfolio.portfolio_helper import (
from openbb_terminal.rich_config import console
from openbb_terminal.stocks.fundamental_analysis.yahoo_finance_model import get_splits
from openbb_terminal.terminal_helper import suppress_stdout
from openbb_terminal.core.session.current_system import get_current_system
# pylint: disable=E1136,W0201,R0902,C0302
# pylint: disable=unsupported-assignment-operation,redefined-outer-name
@@ -196,7 +197,7 @@ class PortfolioEngine:
# Load transactions from file
if path.endswith(".xlsx"):
if str(environ.get("DEBUG_MODE", "false")).lower() != "true":
if not get_current_system().DEBUG_MODE:
warnings.filterwarnings(
"ignore", category=UserWarning, module="openpyxl"
)

View File

@@ -21,7 +21,7 @@ from openbb_terminal.core.config.paths import (
SETTINGS_ENV_FILE,
STYLES_DIRECTORY_REPO,
)
from openbb_terminal.core.session.constants import CHARTS_TABLES_URL, COLORS_URL
from openbb_terminal.core.session.constants import BackendEnvironment
from openbb_terminal.core.session.current_user import (
get_current_user,
is_local,
@@ -231,7 +231,7 @@ class SettingsController(BaseController):
" Then, place the downloaded file 'openbb_config.richstyle.json'"
f" inside {get_current_user().preferences.USER_STYLES_DIRECTORY} or "
f"{STYLES_DIRECTORY_REPO}. If you have a hub account you can change colors "
f"here {COLORS_URL}.",
f"here {BackendEnvironment.HUB_URL + 'app/terminal/theme'}.",
)
if other_args and "-" not in other_args[0][0]:
other_args.insert(0, "-s")
@@ -246,6 +246,7 @@ class SettingsController(BaseController):
value=ns_parser.style,
type_="settings",
auth_header=get_current_user().profile.get_auth_header(),
base_url=BackendEnvironment.HUB_URL,
)
console.print("")
console.print("Colors updated.")
@@ -266,7 +267,7 @@ class SettingsController(BaseController):
dest="style",
choices=["dark", "light"],
help="Choose chart style. If you have a hub account you can change theme "
f"here {CHARTS_TABLES_URL}.",
f"here {BackendEnvironment.HUB_URL + 'app/terminal/theme/charts-tables'}.",
required="-h" not in other_args and "--help" not in other_args,
)
if other_args and "-" not in other_args[0][0]:
@@ -282,6 +283,7 @@ class SettingsController(BaseController):
value=ns_parser.style,
type_="terminal_style",
auth_header=get_current_user().profile.get_auth_header(),
base_url=BackendEnvironment.HUB_URL,
)
console.print("")
theme.apply_style(ns_parser.style)
@@ -303,7 +305,7 @@ class SettingsController(BaseController):
dest="style",
choices=["dark", "light"],
help="Choose table style. If you have a hub account you can change theme "
f"here {CHARTS_TABLES_URL}.",
f"here {BackendEnvironment.HUB_URL + 'app/terminal/theme/charts-tables'}.",
required="-h" not in other_args and "--help" not in other_args,
)
if other_args and "-" not in other_args[0][0]:
@@ -319,6 +321,7 @@ class SettingsController(BaseController):
value=ns_parser.style,
type_="terminal_style",
auth_header=get_current_user().profile.get_auth_header(),
base_url=BackendEnvironment.HUB_URL,
)
console.print("")
console.print("Table theme updated.\n")

View File

@@ -8,7 +8,7 @@ import os
from pathlib import Path
from typing import List, Optional
from openbb_terminal.core.session.constants import SOURCES_URL
from openbb_terminal.core.session.constants import BackendEnvironment
# IMPORTATION THIRDPARTY
# IMPORTATION INTERNAL
@@ -54,7 +54,7 @@ class SourcesController(BaseController):
if Path(sources_file).exists() and os.stat(sources_file).st_size > 0:
self.source = sources_file
else:
self.source = SOURCES_URL
self.source = BackendEnvironment.HUB_URL + "app/terminal/data-sources"
def parse_input(self, an_input: str) -> List:
"""Parse controller input
@@ -176,6 +176,7 @@ class SourcesController(BaseController):
key="features_sources",
value=choices,
auth_header=get_current_user().profile.get_auth_header(),
base_url=BackendEnvironment.BASE_URL,
)
console.print("")
console.print(

View File

@@ -33,7 +33,7 @@ from openbb_terminal.core.config.paths import (
REPOSITORY_DIRECTORY,
SETTINGS_ENV_FILE,
)
from openbb_terminal.core.session.constants import SCRIPT_TAGS
from openbb_terminal.core.session import constants
from openbb_terminal.core.log.generation.custom_logger import log_terminal
from openbb_terminal.core.session import session_controller
from openbb_terminal.core.session.current_system import set_system_variable
@@ -197,9 +197,9 @@ class TerminalController(BaseController):
"-p": "--public",
"--local": None,
"-l": "--local",
"--tag1": {c: None for c in SCRIPT_TAGS},
"--tag2": {c: None for c in SCRIPT_TAGS},
"--tag3": {c: None for c in SCRIPT_TAGS},
"--tag1": {c: None for c in constants.SCRIPT_TAGS},
"--tag2": {c: None for c in constants.SCRIPT_TAGS},
"--tag3": {c: None for c in constants.SCRIPT_TAGS},
}
self.completer = NestedCompleter.from_nested_dict(choices)
@@ -1100,6 +1100,7 @@ def run_routine(file: str, routines_args=Optional[str]):
def main(
debug: bool,
dev: bool,
path_list: List[str],
routines_args: Optional[List[str]] = None,
**kwargs,
@@ -1110,6 +1111,8 @@ def main(
----------
debug : bool
Whether to run the terminal in debug mode
dev:
Points backend towards development environment instead of production
test : bool
Whether to run the terminal in integrated test mode
filtert : str
@@ -1129,6 +1132,11 @@ def main(
if debug:
set_system_variable("DEBUG_MODE", True)
if dev:
set_system_variable("DEV_BACKEND", True)
constants.BackendEnvironment.BASE_URL = "https://payments.openbb.dev/"
constants.BackendEnvironment.HUB_URL = "https://my.openbb.dev/"
cfg.start_plot_backend()
if isinstance(path_list, list) and path_list[0].endswith(".openbb"):
@@ -1156,6 +1164,13 @@ def parse_args_and_run():
default=False,
help="Runs the terminal in debug mode.",
)
parser.add_argument(
"--dev",
dest="dev",
action="store_true",
default=False,
help="Points backend towards development environment instead of production",
)
parser.add_argument(
"--file",
help="The path or .openbb file to run.",
@@ -1227,6 +1242,7 @@ def parse_args_and_run():
main(
ns_parser.debug,
ns_parser.dev,
ns_parser.path,
ns_parser.routine_args,
module=ns_parser.module,

View File

@@ -23,7 +23,7 @@ from openbb_terminal import thought_of_the_day as thought
from openbb_terminal.base_helpers import load_env_files
from openbb_terminal.core.config.paths import HIST_FILE_PATH, SETTINGS_ENV_FILE
from openbb_terminal.core.plots.backend import plots_backend
from openbb_terminal.core.session.constants import REGISTER_URL
from openbb_terminal.core.session.constants import BackendEnvironment
from openbb_terminal.core.session.current_system import get_current_system
from openbb_terminal.core.session.current_user import (
get_current_user,
@@ -257,7 +257,8 @@ def print_guest_block_msg():
console.print(
"[info]You are currently logged as a guest.[/info]\n"
"[info]Login to use this feature.[/info]\n\n"
f"[info]If you don't have an account, you can create one here: [/info][cmds]{REGISTER_URL}\n[/cmds]"
"[info]If you don't have an account, you can create one here: [/info]"
f"[cmds]{BackendEnvironment.HUB_URL + 'register'}\n[/cmds]"
)
@@ -369,6 +370,7 @@ def reset(queue: Optional[List[str]] = None):
plots_backend().close(reset=True)
load_env_files()
debug = get_current_system().DEBUG_MODE
dev = get_current_system().DEV_BACKEND
try:
# save the current user
@@ -399,7 +401,7 @@ def reset(queue: Optional[List[str]] = None):
if is_local():
from openbb_terminal.terminal_controller import main
main(debug, queue_list, module="") # type: ignore
main(debug, dev, queue_list, module="") # type: ignore
else:
from openbb_terminal.core.session import session_controller

View File

@@ -34,8 +34,9 @@ def main():
and ("--login" in sys.argv[1:] or is_installer())
and sys.stdin.isatty()
)
dev = "--dev" in sys.argv[1:]
session_controller.main(prompt=prompt_login)
session_controller.main(prompt=prompt_login, dev=dev)
if __name__ == "__main__":

View File

@@ -46,7 +46,7 @@ def test_create_session_success(email, password):
assert response.json() == TEST_RESPONSE
mock_post.assert_called_once_with(
url=hub_model.BASE_URL + "login",
url=hub_model.BackendEnvironment.BASE_URL + "login",
json={"email": email, "password": password, "remember": True},
timeout=hub_model.TIMEOUT,
)
@@ -113,7 +113,7 @@ def test_create_session_from_token_success(mocker, token):
assert response.json() == TEST_RESPONSE
mock_post.assert_called_once_with(
url=hub_model.BASE_URL + "sdk/login",
url=hub_model.BackendEnvironment.BASE_URL + "sdk/login",
json={"token": token},
timeout=hub_model.TIMEOUT,
)
@@ -151,7 +151,7 @@ def test_delete_session_success(auth_header, token):
assert response.status_code == 200
mock_post.assert_called_once_with(
url=hub_model.BASE_URL + "logout",
url=hub_model.BackendEnvironment.BASE_URL + "logout",
headers={"Authorization": "Bearer test_token"},
json={"token": "test_token"},
timeout=hub_model.TIMEOUT,
@@ -336,7 +336,7 @@ def test_fetch_user_configs_success(token_type, access_token):
assert result == mock_response
requests_get_mock.assert_called_once()
_, kwargs = requests_get_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "terminal/user"
assert kwargs["headers"] == {
"Authorization": f"{token_type.title()} {access_token}"
}
@@ -352,7 +352,7 @@ def test_fetch_user_configs_failure():
result = hub_model.fetch_user_configs(session)
assert isinstance(result, requests.Response)
get_mock.assert_called_once_with(
url=hub_model.BASE_URL + "terminal/user",
url=hub_model.BackendEnvironment.BASE_URL + "terminal/user",
headers={"Authorization": "Bearer abc123"},
timeout=hub_model.TIMEOUT,
)
@@ -366,7 +366,7 @@ def test_fetch_user_configs_connection_error():
result = hub_model.fetch_user_configs(session)
assert result is None
get_mock.assert_called_once_with(
url=hub_model.BASE_URL + "terminal/user",
url=hub_model.BackendEnvironment.BASE_URL + "terminal/user",
headers={"Authorization": "Bearer abc123"},
timeout=hub_model.TIMEOUT,
)
@@ -378,7 +378,7 @@ def test_fetch_user_configs_timeout():
result = hub_model.fetch_user_configs(session)
assert result is None
get_mock.assert_called_once_with(
url=hub_model.BASE_URL + "terminal/user",
url=hub_model.BackendEnvironment.BASE_URL + "terminal/user",
headers={"Authorization": "Bearer abc123"},
timeout=hub_model.TIMEOUT,
)
@@ -390,7 +390,7 @@ def test_fetch_user_configs_exception():
result = hub_model.fetch_user_configs(session)
assert result is None
get_mock.assert_called_once_with(
url=hub_model.BASE_URL + "terminal/user",
url=hub_model.BackendEnvironment.BASE_URL + "terminal/user",
headers={"Authorization": "Bearer abc123"},
timeout=hub_model.TIMEOUT,
)
@@ -415,7 +415,7 @@ def test_upload_config_success(key, value, type_, auth_header):
assert result.status_code == mock_response.status_code
requests_patch_mock.assert_called_once()
_, kwargs = requests_patch_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "terminal/user"
assert kwargs["headers"] == {"Authorization": f"{auth_header}"}
assert kwargs["json"] == {"key": f"features_{type_}.{key}", "value": value}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -434,7 +434,7 @@ def test_upload_config_failure():
assert result.status_code == mock_response.status_code
requests_patch_mock.assert_called_once()
_, kwargs = requests_patch_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "terminal/user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"key": "features_settings.key", "value": "value"}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -451,7 +451,7 @@ def test_upload_config_connection_error():
assert result is None
requests_patch_mock.assert_called_once()
_, kwargs = requests_patch_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "terminal/user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"key": "features_settings.key", "value": "value"}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -468,7 +468,7 @@ def test_upload_config_timeout():
assert result is None
requests_patch_mock.assert_called_once()
_, kwargs = requests_patch_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "terminal/user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"key": "features_settings.key", "value": "value"}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -485,7 +485,7 @@ def test_upload_config_exception():
assert result is None
requests_patch_mock.assert_called_once()
_, kwargs = requests_patch_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "terminal/user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"key": "features_settings.key", "value": "value"}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -504,7 +504,7 @@ def test_clear_user_configs_success():
assert result.status_code == mock_response.status_code
requests_put_mock.assert_called_once()
_, kwargs = requests_put_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"config": {}}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -523,7 +523,7 @@ def test_clear_user_configs_failure():
assert result.status_code == mock_response.status_code
requests_put_mock.assert_called_once()
_, kwargs = requests_put_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"config": {}}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -539,7 +539,7 @@ def test_clear_user_configs_timeout():
assert result is None
requests_put_mock.assert_called_once()
_, kwargs = requests_put_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"config": {}}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -555,7 +555,7 @@ def test_clear_user_configs_connection_error():
assert result is None
requests_put_mock.assert_called_once()
_, kwargs = requests_put_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"config": {}}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -570,7 +570,7 @@ def test_clear_user_configs_exception():
assert result is None
requests_put_mock.assert_called_once()
_, kwargs = requests_put_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "user"
assert kwargs["url"] == hub_model.BackendEnvironment.BASE_URL + "user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"config": {}}
assert kwargs["timeout"] == hub_model.TIMEOUT