Files
OpenBB/openbb_terminal/decorators.py
montezdesousa 475ebb5acd [WIP] Migrate user, feature flags and configurations to dataclass (#4309)
* implement user and change is guest

* replace User methods

* move remaining functions to user

* fix bug

* portfolio test

* fix tests

* fix tests

* uncomment skip

* ruff

* start credentials model implementation

* change deault structure

* refacto quandl

* change default struct and file names

* bug

* start using global user

* add comments

* move update flair

* change cfg references in keys model

* reddit & fmp

* refactore additional keys

* remaing config keys

* remove unsude imports and fix hub keys

* ruff

* fix line too long

* unblock unittests

* fix keys model tests

* remove os patch

* fix account controller tests

* fix account controller tests

* fix account model

* account fixed

* fix user tests

* User Model

* User Model

* User Model

* Move session folder

* User Model : grouping the models

* User Model : fix bugs

* Config Plot + bug fix

* User Model : Refactoring plots

* Feature flags

* Remove dup

* clean comments a fix some vars

* fix feature flags controller

* refactor obbff from settings controller

* refactor a bunch of obbff variables

* fix bug blocking terminal

* fix integration tests

* refactor controllers with obbff

* refactor remaining ffs

* remove comments

* log not started

* mispelled variable

* set current user on local model

* User Model : moving files + updating

* User Preferences

* User : Refactor is_guest function + bug fix

* User : refactor is_guest function

* Fix conftest.py

* remove lost obbffs

* typo on fileoverwrite

* Plot config: move variables and start plot dpi

* User : tests

* refactor plot dpi references

* remove plot dpi imports

* refactor some config terminal leftover

* /account/sync : fix bug

* remove configs reload

* start path refactor

* installation paths vs user paths

* remove cfg_plot

* Tests : User Refactoring

* user prefix only for preferences

* user prefix only for preferences

* move user paths

* remove comment

* update apply remote configs

* fix tz not updating

* save some copys

* small fix

* create interface for credentials and preferences

* wrong docstrings fixed

* ruff core

* fix some pref setting

* login is better

* ruff

* ruff

* remove Literal

* add small comment

* Tests : User Refactoring

* Credentials Model : add DataBento

* Fix helper_funcs

* Fixing code

* Tests : fixing

* User Model : freezing the models

* Fixed Income + Databento

* Tests : fixing keys

* black

* ruff

* Tests : user model

* Tests : user model

* Fix linting

* Fix linting

* Linting

* Linting

* Fixing code and tests

* Fix tests

* mypy

* SDK

* Clean ruff cache

* Fix syntax issue

* Update fred_view

* Black

* Linting

* Update code

* Update tests

* Linting

* Linting

* Tests

* Black

* Linting

* Linting

* Mock os.listdir to avoid looking for file that doesnt exist

* Mock options paths

* lint

* Tests : fix

* Code : update

* Tests + Linting

* Tests

* Ruff

* Code : update

* Tests

* Code : update

* Fix workflow

* Code : update

---------

Co-authored-by: Chavithra PARANA <chavithra@gmail.com>
Co-authored-by: luqazino@gmail.com <luqazino@gmail.com>
Co-authored-by: James Maslek <jmaslek11@gmail.com>
2023-03-05 00:37:19 +01:00

154 lines
5.0 KiB
Python

"""Decorators"""
__docformat__ = "numpy"
import functools
import logging
import os
from ssl import SSLError
import pandas as pd
from requests.exceptions import RequestException
from openbb_terminal.core.session.current_user import (
get_current_user,
set_current_user,
)
from openbb_terminal.rich_config import console
logger = logging.getLogger(__name__)
def log_start_end(func=None, log=None):
"""Wrap function to add a log entry at execution start and end.
Parameters
----------
func : optional
Function, by default None
log : optional
Logger, by default None
Returns
-------
Wrapped function
"""
assert callable(func) or func is None # noqa: S101
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
logging_name = ""
args_passed_in_function = [
repr(a) for a in args if isinstance(a, (pd.DataFrame, pd.Series)) or a
]
if (
len(args) == 2
and args_passed_in_function
and (
"__main__.TerminalController" in args_passed_in_function[0]
or (
"openbb_terminal." in args_passed_in_function[0]
and "_controller" in args_passed_in_function[0]
)
)
):
logging_name = args_passed_in_function[0].split()[0][1:]
args_passed_in_function = args_passed_in_function[1:]
logger_used = logging.getLogger(logging_name) if logging_name else log
logger_used.info(
"START",
extra={"func_name_override": func.__name__},
)
if str(os.environ.get("DEBUG_MODE", "false")).lower() == "true":
value = func(*args, **kwargs)
log.info("END", extra={"func_name_override": func.__name__})
return value
try:
value = func(*args, **kwargs)
logger_used.info("END", extra={"func_name_override": func.__name__})
return value
except KeyboardInterrupt:
logger_used.info(
"Interrupted by user",
extra={"func_name_override": func.__name__},
)
return []
except RequestException as e:
console.print(
"[red]There was an error connecting to the API."
" Please try again later.\n[/red]"
)
logger_used.exception(
"Exception: %s",
str(e),
extra={"func_name_override": func.__name__},
)
return []
except SSLError as e:
console.print(
"[red]There was an error connecting to the API."
" Please check whether your wifi is blocking this site.\n[/red]"
)
logger_used.exception(
"Exception: %s",
str(e),
extra={"func_name_override": func.__name__},
)
return []
except Exception as e:
console.print(f"[red]Error: {e}\n[/red]")
logger_used.exception(
"Exception: %s",
str(e),
extra={"func_name_override": func.__name__},
)
return []
return wrapper
return decorator(func) if callable(func) else decorator
# pylint: disable=import-outside-toplevel
def check_api_key(api_keys):
"""
Wrapper around the view or controller function and
print message statement to the console if API keys are not yet defined.
"""
def decorator(func):
@functools.wraps(func)
def wrapper_decorator(*args, **kwargs):
if get_current_user().preferences.ENABLE_CHECK_API:
current_user = get_current_user()
undefined_apis = []
for key in api_keys:
# Get value of the API Keys
if (
getattr(current_user.credentials, key) == "REPLACE_ME"
) and key not in ["API_KEY_ALPHAVANTAGE"]:
undefined_apis.append(key)
if undefined_apis:
undefined_apis_name = ", ".join(undefined_apis)
console.print(
f"[red]{undefined_apis_name} not defined. "
"Set API Keys in ~/.openbb_terminal/.env or under keys menu.[/red]"
) # pragma: allowlist secret
return None
return func(*args, **kwargs)
return wrapper_decorator
return decorator
def disable_check_api():
current_user = get_current_user()
current_user.preferences.ENABLE_CHECK_API = False
set_current_user(current_user)