Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Endpoints #226

Merged
merged 6 commits into from
Apr 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ jobs:
id: cache-poetry
with:
path: ~/.virtualenvs
key: poetry|pre-commit|v2|${{ matrix.os }}|${{ env.PY }}|${{ hashFiles('poetry.lock') }}
key: poetry|pre-commit|v3|${{ matrix.os }}|${{ env.PY }}|${{ hashFiles('poetry.lock') }}
restore-keys: |
poetry|pre-commit|v2|${{ matrix.os }}|${{ env.PY }}|
poetry|pre-commit|v3|${{ matrix.os }}|${{ env.PY }}|
- name: Install Project Dependencies (Poetry)
run: |
poetry install -vvv
Expand Down Expand Up @@ -78,9 +78,9 @@ jobs:
id: cache-poetry
with:
path: ~/.virtualenvs
key: poetry|v2|${{ matrix.os }}|${{ env.PY }}|${{ hashFiles('poetry.lock') }}
key: poetry|v3|${{ matrix.os }}|${{ env.PY }}|${{ hashFiles('poetry.lock') }}
restore-keys: |
poetry|v2|${{ matrix.os }}|${{ env.PY }}|
poetry|v3|${{ matrix.os }}|${{ env.PY }}|
- name: Install Project Dependencies (Poetry)
run: |
poetry install -vvv
Expand Down
1 change: 1 addition & 0 deletions newsfragments/226.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Refactor endpoints to ursl and make better use of yarl.
11 changes: 0 additions & 11 deletions pyrh/common.py

This file was deleted.

135 changes: 0 additions & 135 deletions pyrh/endpoints.py

This file was deleted.

5 changes: 2 additions & 3 deletions pyrh/models/base.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"""Base Model."""

from types import SimpleNamespace
from typing import Any, Mapping
from typing import Any, Dict, Mapping

from marshmallow import INCLUDE, Schema, post_load

from pyrh.common import JSON


JSON = Dict[str, Any]
MAX_REPR_LEN = 50


Expand Down
4 changes: 1 addition & 3 deletions pyrh/models/portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@

from marshmallow import fields, post_load

from pyrh.common import JSON

from .base import BaseModel, BaseSchema
from .base import JSON, BaseModel, BaseSchema


class Portfolio(BaseModel):
Expand Down
40 changes: 17 additions & 23 deletions pyrh/models/sessionmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import uuid
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union, cast
from typing import TYPE_CHECKING, Any, Dict, Optional, Union, cast
from urllib.request import getproxies

import certifi
Expand All @@ -13,29 +13,24 @@
from requests.structures import CaseInsensitiveDict
from yarl import URL

from pyrh.common import API_BASE, JSON
from pyrh import urls
from pyrh.exceptions import AuthenticationError

from .base import BaseModel, BaseSchema
from .base import JSON, BaseModel, BaseSchema
from .oauth import CHALLENGE_TYPE_VAL, OAuth, OAuthSchema


CLIENT_ID: str = "c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS"
"""Robinhood client id."""

# Types
if TYPE_CHECKING: # pragma: no cover
CaseInsensitiveDictType = CaseInsensitiveDict[str]
else:
CaseInsensitiveDictType = CaseInsensitiveDict
Proxies = Dict[str, str]

# Endpoints
OAUTH: URL = API_BASE.with_path("/oauth2/token/")
OAUTH_REVOKE: URL = API_BASE.with_path("/oauth2/revoke_token/")
CHALLENGE: Callable[[str], URL] = lambda cid: API_BASE.with_path(
f"/challenge/{cid}/respond/"
)

Proxies = Dict[str, str]
# Constants
CLIENT_ID: str = "c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS"
"""Robinhood client id."""
HEADERS: CaseInsensitiveDictType = CaseInsensitiveDict(
{
"Accept": "*/*",
Expand All @@ -48,15 +43,11 @@
}
)
"""Headers used when performing requests with robinhood api."""

# 8.5 days (you have a small window to refresh after this)
# I would refresh the token proactively every day in a script
EXPIRATION_TIME: int = 734000
"""Default expiration time for requests."""

# TODO: Watch this issue and remove the F811 ignores when it is fixed
# https://gitlab.com/pycqa/flake8/-/merge_requests/417 (we need at least pyflakes 2.2.0)


class SessionManager(BaseModel):
"""Mange connectivity with Robinhood API.
Expand Down Expand Up @@ -312,7 +303,7 @@ def _challenge_oauth2(self, oauth: OAuth, oauth_payload: JSON) -> OAuth:

"""
# login challenge
challenge_url = CHALLENGE(oauth.challenge.id)
challenge_url = urls.build_challenge(oauth.challenge.id)
print(
f"Input challenge code from {oauth.challenge.type.capitalize()} "
f"({oauth.challenge.remaining_attempts}/"
Expand All @@ -338,7 +329,7 @@ def _challenge_oauth2(self, oauth: OAuth, oauth_payload: JSON) -> OAuth:
return cast(
OAuth,
self.post(
OAUTH,
urls.OAUTH,
data=oauth_payload,
headers=challenge_header,
auto_login=False,
Expand Down Expand Up @@ -374,7 +365,7 @@ def _mfa_oauth2(self, oauth_payload: JSON, attempts: int = 3) -> OAuth:
mfa_code = input()
oauth_payload["mfa_code"] = mfa_code
oauth, res = self.post(
OAUTH,
urls.OAUTH,
data=oauth_payload,
raise_errors=False,
auto_login=False,
Expand Down Expand Up @@ -413,7 +404,7 @@ def _login_oauth2(self) -> None:
}

oauth = self.post(
OAUTH,
urls.OAUTH,
data=oauth_payload,
raise_errors=False,
auto_login=False,
Expand Down Expand Up @@ -456,7 +447,10 @@ def _refresh_oauth2(self) -> None:
self.session.headers.pop("Authorization", None)
try:
oauth = self.post(
OAUTH, data=relogin_payload, auto_login=False, schema=OAuthSchema()
urls.OAUTH,
data=relogin_payload,
auto_login=False,
schema=OAuthSchema(),
)
except HTTPError:
raise AuthenticationError("Failed to refresh token")
Expand All @@ -472,7 +466,7 @@ def logout(self) -> None:
"""
logout_payload = {"client_id": CLIENT_ID, "token": self.oauth.refresh_token}
try:
self.post(OAUTH_REVOKE, data=logout_payload, auto_login=False)
self.post(urls.OAUTH_REVOKE, data=logout_payload, auto_login=False)
self.oauth = OAuth()
self.session.headers.pop("Authorization", None)
except HTTPError:
Expand Down
Loading