Files
OpenBB/openbb_terminal/base_helpers.py
Henrique Joaquim 46b230f146 Minor fixes on login (#4234)
* block logout

* fix default behaviour to no ask for creds

* enables to use --login on
Welcome to OpenBB Terminal v2.3.1
╭─────────────────────────────────── Home ───────────────────────────────────╮
│                                                                            │
│ Information, guides and support for the OpenBB Terminal:                   │
│     intro              introduction on the OpenBB Terminal                 │
│     about              discover the capabilities of the OpenBB Terminal (h │
│     support            pre-populate a support ticket for our team to evalu │
│     survey             fill in our 2-minute survey so we better understand │
│     update             attempt to update the terminal automatically (GitHu │
│     wiki               search for an expression in Wikipedia (https://www. │
│     news               display news articles based on term and data source │
│                                                                            │
│ Configure your own terminal:                                               │
│ >   keys               set API keys and check their validity               │
│ >   featflags          enable and disable feature flags                    │
│ >   sources            select your preferred data sources                  │
│ >   settings           tune settings (export folder, timezone, language, p │
│                                                                            │
│ Record and execute your own .openbb routine scripts:                       │
│     record             start recording current session                     │
│     stop               stop session recording and convert to .openbb routi │
│     exe                execute .openbb routine scripts (use exe --example  │
│                                                                            │
│ Main menu:                                                                 │
│ >   stocks             access historical pricing data, options, sector and │
│ >   crypto             dive into onchain data, tokenomics, circulation sup │
│ >   etf                exchange traded funds. Historical pricing, compare  │
│ >   economy            global macroeconomic data, e.g. futures, yield, tre │
│ >   forex              foreign exchanges, quotes, forward rates for curren │
│ >   futures            commodities, bonds, index, bitcoin and forex        │
│ >   alternative        alternative datasets, such as COVID and open source │
│ >   funds              mutual funds search, overview, holdings and sector  │
│                                                                            │
│ OpenBB Toolkits:                                                           │
│ >   econometrics       statistical and quantitative methods for relationsh │
│ >   forecast           timeseries forecasting with machine learning        │
│ >   portfolio          perform portfolio optimization and look at portfoli │
│ >   dashboards         interactive dashboards using voila and jupyter note │
│ >   reports            customizable research reports through jupyter noteb │
│                                                                            │
╰─────────────────────────────── OpenBB Terminal v2.3.1 (https://openbb.co) ─╯
You are using the latest stable version

2023 Feb 14, 06:39 (🦋) / $

[h] help menu    [q] return to previous menu    [e] exit terminal    [cmd -h] s
                                                                               e
                            2023 Feb 14, 06:39 (🦋) / $
The OpenBB Terminal is the result of a strong community building an investment research platform for everyone, anywhere.

We are always eager to welcome new contributors and you can find our open jobs here:
https://www.openbb.co/company/careers#open-roles

Join us           : https://openbb.co/discord
Follow us         : https://twitter.com/openbb_finance
Ask support       : https://openbb.co/support
Request a feature : https://openbb.co/request-a-feature

Fill in our 2-minute survey so we better understand how we can improve the OpenBB Terminal at https://openbb.co/survey

In the meantime access investment research from your chatting platform using the OpenBB Bot
Try it today, for FREE: https://openbb.co/products/bot

* reverting the condition to the original state

* openbb to match python terminal.py

* adding unauthorized

* reverting changes

* getting the value of the status

---------

Co-authored-by: Diogo Sousa <montezdesousa@gmail.com>
Co-authored-by: James Maslek <jmaslek11@gmail.com>
2023-02-15 14:55:22 +00:00

155 lines
4.2 KiB
Python

# This is for helpers that do NOT import any OpenBB Modules
import importlib
import logging
import os
import sys
from typing import Any, Callable, List, Literal, Optional
from dotenv import load_dotenv
from rich.console import Console
from openbb_terminal.core.config.paths import (
PACKAGE_ENV_FILE,
REPOSITORY_ENV_FILE,
USER_ENV_FILE,
)
console = Console()
menus = Literal["", "featflags", "settings"]
def handle_error(name: str, default: Any, menu: menus = ""):
"""Handles the error by returning the default value and printing an
informative error message.
Parameters
----------
name: str
The name of the environment variable
default: Any
The value to return if the converter fails
menu: menus
If provided, will tell the user where to fix the setting
Returns
----------
Any
The default value
"""
base = f"[red]Invalid variable provided for variable '{name}'."
if menu:
base += f" Please change the setting in the `{menu}` menu."
base += "[/red]\n"
console.print(base)
return default
def load_env_vars(
name: str, converter: Callable, default: Any, menu: menus = ""
) -> Any:
"""Loads an environment variable and attempts to convert it to the correct data type.
Will return the provided default if it fails
Parameters
----------
name: str
The name of the environment variable
converter: Callable
The function to convert the env variable to the desired format
default: Any
The value to return if the converter fails
menu: menus
If provided, will tell the user where to fix the setting
Returns
----------
Any
The value or the default
"""
raw_var = os.getenv(name, str(default))
try:
return converter(raw_var)
except ValueError:
return handle_error(name, default, menu)
except AttributeError:
return handle_error(name, default, menu)
except TypeError:
return handle_error(name, default, menu)
def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = str(val).lower()
if val in ("y", "yes", "t", "true", "on", "1"):
output = True
elif val in ("n", "no", "f", "false", "off", "0"):
output = False
else:
raise ValueError(f"invalid truth value {val}")
return output
def load_dotenv_and_reload_configs():
"""
Loads the dotenv files in the following order:
1. Repository .env file
2. Package .env file
3. User .env file
This allows the user to override the package settings with their own
settings, and the package to override the repository settings.
openbb_terminal modules are reloaded to refresh config files with new env,
otherwise they will use cache with old variables.
"""
load_dotenv(REPOSITORY_ENV_FILE, override=True)
load_dotenv(PACKAGE_ENV_FILE, override=True)
load_dotenv(USER_ENV_FILE, override=True)
reload_openbb_config_modules()
def reload_openbb_config_modules():
"""Reloads openbb config modules"""
reload_modules(
to_reload=[
"openbb_terminal.config_plot",
"openbb_terminal.config_terminal",
"openbb_terminal.feature_flags",
"openbb_terminal.core.config",
]
)
def reload_modules(to_reload: List[str]):
"""Reloads modules"""
modules = sys.modules.copy()
for module in modules:
if module in to_reload:
importlib.reload(sys.modules[module])
def remove_log_handlers():
"""Remove the log handlers - needs to be done before reloading modules."""
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
def clear_openbb_env_vars(exceptions: Optional[List[str]] = None):
"""Clear openbb environment variables."""
for v in os.environ:
if v.startswith("OPENBB"):
if not exceptions:
os.environ.pop(v)
elif v not in exceptions:
os.environ.pop(v)