Skip to content

Commit

Permalink
refactored prepare_host() into a function to reduce cript.API file …
Browse files Browse the repository at this point in the history
…bulk

* easily refactored and put `prepare_host()` into a function that reduces the bulk of the api.py file
* wrote docstrings for `prepare_host()`
* optimized imports after moving `prepare_host()` to its own function in another file
* formatted everything with black
  • Loading branch information
nh916 committed Sep 20, 2023
1 parent 4b4c3ff commit 3426095
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 19 deletions.
21 changes: 2 additions & 19 deletions src/cript/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import logging
import os
import uuid
import warnings
from pathlib import Path
from typing import Any, Dict, List, Optional, Union

Expand All @@ -20,12 +19,11 @@
CRIPTAPISaveError,
CRIPTConnectionError,
CRIPTDuplicateNameError,
InvalidHostError,
InvalidVocabulary,
)
from cript.api.paginator import Paginator
from cript.api.utils.get_host_token import resolve_host_and_token
from cript.api.utils.helper_functions import _get_node_type_from_json
from cript.api.utils.helper_functions import _get_node_type_from_json, prepare_host
from cript.api.utils.save_helper import (
_fix_node_save,
_get_uuid_from_error_message,
Expand Down Expand Up @@ -216,7 +214,7 @@ def __init__(self, host: Union[str, None] = None, api_token: Union[str, None] =
api_token = authentication_dict["api_token"]
storage_token = authentication_dict["storage_token"]

self._host = self._prepare_host(host=host) # type: ignore
self._host = prepare_host(host=host, api_handle=self._api_handle, api_version=self._api_version) # type: ignore
self._api_token = api_token # type: ignore
self._storage_token = storage_token # type: ignore

Expand Down Expand Up @@ -328,21 +326,6 @@ def verbose(self, new_verbose_value: bool) -> None:
self._verbose = new_verbose_value
self._set_logger(verbose=new_verbose_value)

@beartype
def _prepare_host(self, host: str) -> str:
# strip ending slash to make host always uniform
host = host.rstrip("/")
host = f"{host}/{self._api_handle}/{self._api_version}"

# if host is using unsafe "http://" then give a warning
if host.startswith("http://"):
warnings.warn("HTTP is an unsafe protocol please consider using HTTPS.")

if not host.startswith("http"):
raise InvalidHostError()

return host

# Use a property to ensure delayed init of s3_client
@property
def _s3_client(self) -> boto3.client: # type: ignore
Expand Down
42 changes: 42 additions & 0 deletions src/cript/api/utils/helper_functions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import json
import warnings
from typing import Dict, List, Union

from beartype import beartype

from cript.api.exceptions import InvalidHostError
from cript.nodes.exceptions import CRIPTJsonNodeError
from cript.nodes.util import _is_node_field_valid

Expand Down Expand Up @@ -41,3 +45,41 @@ def _get_node_type_from_json(node_json: Union[Dict, str]) -> str:
# if invalid then raise error
else:
raise CRIPTJsonNodeError(node_list=node_type_list, json_str=str(node_json))


@beartype
def prepare_host(host: str, api_handle: str, api_version: str) -> str:
"""
Takes the pieces of the API URL, constructs a full URL, and returns it
Parameters
----------
host: str
api host such as `https://api.criptapp.org`
api_handle: str
the api prefix of `/api/`
api_version: str
the api version `/v1/`
Returns
-------
str
full API url such as `https://api.criptapp.org/api/v1`
Warns
-----
UserWarning
If `host` is using "http" it gives the user a warning that HTTP is insecure and the user should use HTTPS
"""
# strip ending slash to make host always uniform
host = host.rstrip("/")
host = f"{host}/{api_handle}/{api_version}"

# if host is using unsafe "http://" then give a warning
if host.startswith("http://"):
warnings.warn("HTTP is an unsafe protocol please consider using HTTPS.")

if not host.startswith("http"):
raise InvalidHostError()

return host

0 comments on commit 3426095

Please sign in to comment.