Skip to content

Commit

Permalink
Merge branch 'develop' into feature/documentation3p0
Browse files Browse the repository at this point in the history
  • Loading branch information
piiq authored Mar 16, 2023
2 parents d310970 + 18b82a7 commit 3532778
Show file tree
Hide file tree
Showing 27 changed files with 346 additions and 532 deletions.
37 changes: 18 additions & 19 deletions openbb_terminal/account/account_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,20 @@
from pathlib import Path
from typing import Dict, List, Optional

from openbb_terminal import (
keys_model,
from openbb_terminal.account.account_model import (
get_diff,
get_routines_info,
)
from openbb_terminal.account.account_model import get_diff, get_routines_info
from openbb_terminal.account.account_view import display_routines_list
from openbb_terminal.core.session import (
hub_model as Hub,
local_model as Local,
)
from openbb_terminal.core.session.current_user import get_current_user, is_local
from openbb_terminal.core.session.preferences_handler import set_preference
from openbb_terminal.core.session.current_user import (
get_current_user,
is_local,
set_preference,
)
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
Expand Down Expand Up @@ -156,16 +159,23 @@ def call_sync(self, other_args: List[str]):

ns_parser = self.parse_known_args_and_warn(parser, other_args)
if ns_parser:
current_user = get_current_user()
if ns_parser.sync is None:
sync = "ON" if current_user.preferences.SYNC_ENABLED is True else "OFF"
sync = (
"ON"
if get_current_user().preferences.SYNC_ENABLED is True
else "OFF"
)
console.print(f"sync is {sync}, use --on or --off to change.")
else:
set_preference(
name="SYNC_ENABLED",
value=ns_parser.sync,
)
sync = "ON" if current_user.preferences.SYNC_ENABLED is True else "OFF"
sync = (
"ON"
if get_current_user().preferences.SYNC_ENABLED is True
else "OFF"
)
console.print(f"[info]sync:[/info] {sync}")

@log_start_end(log=logger)
Expand Down Expand Up @@ -489,17 +499,6 @@ def call_generate(self, other_args: List[str]) -> None:
if token:
console.print(f"\n[info]Token:[/info] {token}\n")

save_to_keys = False
if not ns_parser.save:
save_to_keys = console.input(
"Would you like to save the token to the keys? (y/n): "
).lower() in ["y", "yes"]

if save_to_keys or ns_parser.save:
keys_model.set_openbb_personal_access_token(
key=token, persist=True, show_output=True
)

@log_start_end(log=logger)
def call_show(self, other_args: List[str]) -> None:
"""Process show command."""
Expand Down
3 changes: 0 additions & 3 deletions openbb_terminal/core/models/credentials_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,6 @@ class CredentialsModel:
API_COINBASE_SECRET: str = "REPLACE_ME"
API_COINBASE_PASS_PHRASE: str = "REPLACE_ME"

# Others
OPENBB_PERSONAL_ACCESS_TOKEN: str = "REPLACE_ME"

def __repr__(self) -> str:
"""Return string representation of model."""
dataclass_repr = ""
Expand Down
1 change: 0 additions & 1 deletion openbb_terminal/core/models/preferences_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ class PreferencesModel:
# Enable interactive matplotlib mode: change variable name to be more descriptive and delete comment
USE_ION: bool = True
USE_WATERMARK: bool = True
# Enable command and source in the figures: change variable name to be more descriptive and delete comment
USE_CMD_LOCATION_FIGURE: bool = True
USE_PROMPT_TOOLKIT: bool = True
USE_PLOT_AUTOSCALING: bool = False
Expand Down
2 changes: 0 additions & 2 deletions openbb_terminal/core/sdk/models/keys_sdk_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ class KeysRoot(Category):
`mykeys`: Get currently set API keys.\n
`news`: Set News key\n
`oanda`: Set Oanda key\n
`openbb`: Set OpenBB Personal Access Token.\n
`polygon`: Set Polygon key\n
`quandl`: Set Quandl key\n
`reddit`: Set Reddit key\n
Expand Down Expand Up @@ -71,7 +70,6 @@ def __init__(self):
self.mykeys = lib.keys_model.get_keys
self.news = lib.keys_model.set_news_key
self.oanda = lib.keys_model.set_oanda_key
self.openbb = lib.keys_model.set_openbb_personal_access_token
self.polygon = lib.keys_model.set_polygon_key
self.quandl = lib.keys_model.set_quandl_key
self.reddit = lib.keys_model.set_reddit_key
Expand Down
73 changes: 0 additions & 73 deletions openbb_terminal/core/session/credentials_handler.py

This file was deleted.

59 changes: 57 additions & 2 deletions openbb_terminal/core/session/current_user.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# IMPORTS STANDARD
import dataclasses
from copy import deepcopy
from typing import Optional
from pathlib import Path
from typing import Optional, Union

# IMPORTS INTERNAL
from openbb_terminal.core.models import (
Expand All @@ -9,7 +11,10 @@
ProfileModel,
UserModel,
)
from openbb_terminal.core.session.env_handler import load_env_to_model, reading_env
from openbb_terminal.core.session.env_handler import (
load_env_to_model,
reading_env,
)

__env_dict = reading_env()
__credentials = load_env_to_model(__env_dict, CredentialsModel)
Expand All @@ -36,6 +41,21 @@ def set_current_user(user: UserModel):
__current_user = user


def get_local_user() -> UserModel:
"""Get local user."""
return deepcopy(__local_user)


def get_env_dict() -> dict:
"""Get env dict."""
return deepcopy(__env_dict)


def get_local_preferences() -> PreferencesModel:
"""Get preferences."""
return deepcopy(__preferences) # type: ignore


def is_local() -> bool:
"""Check if user is guest.
Expand Down Expand Up @@ -65,3 +85,38 @@ def copy_user(
)

return user_copy


def set_preference(
name: str,
value: Union[bool, Path, str],
):
"""Set preference
Parameters
----------
name : str
Preference name
value : Union[bool, Path, str]
Preference value
"""
current_user = get_current_user()
updated_preferences = dataclasses.replace(current_user.preferences, **{name: value})
updated_user = dataclasses.replace(current_user, preferences=updated_preferences)
set_current_user(updated_user)


def set_credential(name: str, value: str):
"""Set credential
Parameters
----------
name : str
Credential name
value : str
Credential value
"""
current_user = get_current_user()
updated_credentials = dataclasses.replace(current_user.credentials, **{name: value})
updated_user = dataclasses.replace(current_user, credentials=updated_credentials)
set_current_user(updated_user)
20 changes: 18 additions & 2 deletions openbb_terminal/core/session/env_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import Any, Dict, Optional, Type, Union

# IMPORTS THIRDPARTY
from dotenv import dotenv_values
from dotenv import dotenv_values, set_key
from pydantic import ValidationError

# IMPORTS INTERNAL
Expand Down Expand Up @@ -53,10 +53,10 @@ def load_env_to_model(
Union[Type[CredentialsModel], Type[PreferencesModel]]
Model with environment variables.
"""
model_name = model.__name__.strip("Model").lower()
try:
return model(**env_dict) # type: ignore
except ValidationError as error:
model_name = model.__name__.strip("Model").lower()
print(f"Error loading {model_name}:")
for err in error.errors():
loc = err.get("loc", None)
Expand All @@ -69,3 +69,19 @@ def load_env_to_model(
print(f" {var_name}: {msg}, using default -> {default}")

return model(**env_dict) # type: ignore
except Exception:
print(f"Error loading {model_name}, using defaults.")
return model() # type: ignore


def write_to_dotenv(name: str, value: str) -> None:
"""Write to .env file.
Parameters
----------
name : str
Name of the variable.
value : str
Value of the variable.
"""
set_key(str(SETTINGS_ENV_FILE), name, str(value))
8 changes: 4 additions & 4 deletions openbb_terminal/core/session/hub_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def fetch_user_configs(
return None


def patch_user_configs(
def upload_config(
key: str,
value: str,
type_: str,
Expand Down Expand Up @@ -565,7 +565,7 @@ def generate_personal_access_token(
Optional[requests.Response]
"""

url = f"{base_url}/sdk/token"
url = f"{base_url}sdk/token"

payload = json.dumps({"days": days})
headers = {
Expand Down Expand Up @@ -612,7 +612,7 @@ def get_personal_access_token(
Optional[requests.Response]
"""

url = f"{base_url}/sdk/token"
url = f"{base_url}sdk/token"

headers = {"Authorization": auth_header}

Expand Down Expand Up @@ -655,7 +655,7 @@ def revoke_personal_access_token(
Optional[requests.Response]
"""

url = f"{base_url}/sdk/token"
url = f"{base_url}sdk/token"

headers = {"Authorization": auth_header}

Expand Down
44 changes: 10 additions & 34 deletions openbb_terminal/core/session/local_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
HIST_FILE_PATH,
SETTINGS_DIRECTORY,
)
from openbb_terminal.core.session.credentials_handler import set_credential
from openbb_terminal.core.session.current_user import get_current_user
from openbb_terminal.core.session.preferences_handler import set_preference
from openbb_terminal.core.session.current_user import (
get_current_user,
get_local_user,
set_credential,
)
from openbb_terminal.rich_config import console

SESSION_FILE_PATH = SETTINGS_DIRECTORY / "session.json"
Expand Down Expand Up @@ -110,38 +112,12 @@ def apply_configs(configs: dict):
configs : dict
The configurations.
"""
if configs:
settings = configs.get("features_settings", {})
sync = update_sync_flag(settings)
if sync:
if settings:
for k, v in settings.items():
set_preference(k, v, login=True)

keys = configs.get("features_keys", {})
if keys:
for k, v in keys.items():
set_credential(k, v, login=True)


def update_sync_flag(settings: dict) -> bool:
"""Update the sync flag.
Parameters
----------
settings : dict
The settings.
Returns
-------
bool
The sync flag.
"""
sync = not (settings and settings.get("SYNC_ENABLED", "true").lower() == "false")

set_preference("SYNC_ENABLED", sync, login=True)
if configs and get_local_user().preferences.SYNC_ENABLED:
credentials = configs.get("features_keys", {}) or {}
for k, v in credentials.items():
set_credential(k, v)

return sync
# TODO: apply other configs here


def get_routine(file_name: str, folder: Optional[Path] = None) -> Optional[str]:
Expand Down
Loading

0 comments on commit 3532778

Please sign in to comment.