Skip to content

Commit 497feba

Browse files
validate_json_schema() function
1 parent 3d57b8b commit 497feba

22 files changed

+557
-223
lines changed

.vscode/settings.json

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,12 @@
33
"tests"
44
],
55
"python.testing.unittestEnabled": false,
6-
"python.testing.pytestEnabled": true
6+
"python.testing.pytestEnabled": true,
7+
"python.testing.unittestArgs": [
8+
"-v",
9+
"-s",
10+
"./tests",
11+
"-p",
12+
"test_*.py"
13+
],
714
}

Makefile

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ help:
55
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
66

77
fmt: ## (Format) - runs black and isort against the codebase
8-
poetry run black ./src/*
9-
poetry run isort ./src/*
8+
poetry run black ./dpytools/*
9+
poetry run isort ./dpytools/*
1010

1111
lint: ## Run the ruff python linter
12-
poetry run ruff ./src/*
12+
poetry run ruff ./dpytools/*
1313

1414
test: ## Run pytest and check test coverage
1515
poetry run pytest --cov-report term-missing --cov=dpytools

dpytools/config/config.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
from .properties.base import BaseProperty
44

5-
class Config:
65

6+
class Config:
77
@staticmethod
88
def from_env(config_dict: Dict[str, BaseProperty]):
99
# TODO = read in and populate property classes as
@@ -34,5 +34,3 @@ def assert_valid_config(self):
3434
# For each of the properties you imbided above, run
3535
# self.type_is_valid()
3636
# self.secondary_validation()
37-
38-
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
from .string import StringProperty
1+
from .string import StringProperty

dpytools/config/properties/base.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from abc import ABCMeta, abstractmethod
22
from dataclasses import dataclass
3-
from typing import Any, Union, Tuple, Optional
3+
from typing import Any
4+
45

56
@dataclass
67
class BaseProperty(metaclass=ABCMeta):
@@ -20,7 +21,7 @@ class BaseProperty(metaclass=ABCMeta):
2021
def type_is_valid(self):
2122
"""
2223
Validate that the property looks like
23-
its of the correct type
24+
its of the correct type
2425
"""
2526
...
2627

@@ -32,4 +33,4 @@ def secondary_validation(self):
3233
Non type based validation you might want to
3334
run against a configuration value.
3435
"""
35-
...
36+
...

dpytools/config/properties/string.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@ class StringProperty(BaseProperty):
1111
def type_is_valid(self):
1212
"""
1313
Validate that the property looks like
14-
its of the correct type
14+
its of the correct type
1515
"""
1616
try:
1717
str(self.value)
1818
except Exception as err:
19-
raise Exception(f"Cannot cast {self.name} value {self.value} to string.") from err
19+
raise Exception(
20+
f"Cannot cast {self.name} value {self.value} to string."
21+
) from err
2022

2123
def secondary_validation_passed(self):
2224
"""
@@ -25,7 +27,7 @@ def secondary_validation_passed(self):
2527
"""
2628
if len(self.value) == 0:
2729
raise ValueError(f"Str value for {self.name} is an empty string")
28-
30+
2931
if self.regex:
3032
# TODO - confirm the value matches the regex
3133
...
@@ -36,4 +38,4 @@ def secondary_validation_passed(self):
3638

3739
if self.max_len:
3840
# TODO - confirm the value matches or is less than the max length
39-
...
41+
...

dpytools/http_clients/base.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
import logging
2+
13
import backoff
24
import requests
35
from requests.exceptions import HTTPError
4-
import logging
56

67

78
# Function to log retry attempts
@@ -15,19 +16,14 @@ def __init__(self, backoff_max=30):
1516
self.backoff_max = backoff_max
1617

1718
# GET request method with exponential backoff
18-
@backoff.on_exception(
19-
backoff.expo,
20-
HTTPError,
21-
max_time=30,
22-
on_backoff=log_retry
23-
)
19+
@backoff.on_exception(backoff.expo, HTTPError, max_time=30, on_backoff=log_retry)
2420
def get(self, url, *args, **kwargs):
2521
"""
2622
Sends a GET request to the specified URL with optional extra arguments.
2723
28-
This method is a thin wrapper around `requests.get()`. Any additional arguments
29-
are passed directly to `requests.get()`. For more information on the available
30-
arguments, refer to the `requests.get()` documentation:
24+
This method is a thin wrapper around `requests.get()`. Any additional arguments
25+
are passed directly to `requests.get()`. For more information on the available
26+
arguments, refer to the `requests.get()` documentation:
3127
https://docs.python-requests.org/en/latest/api/#requests.get
3228
3329
Args:
@@ -40,22 +36,22 @@ def get(self, url, *args, **kwargs):
4036
Raises:
4137
HTTPError: If the request fails for a network-related reason.
4238
"""
43-
return self._handle_request('GET', url, *args, **kwargs)
39+
return self._handle_request("GET", url, *args, **kwargs)
4440

4541
# POST request method with exponential backoff
4642
@backoff.on_exception(
47-
backoff.expo,
43+
backoff.expo,
4844
HTTPError,
49-
max_time=30,
45+
max_time=30,
5046
on_backoff=log_retry,
5147
)
5248
def post(self, url, *args, **kwargs):
5349
"""
5450
Sends a POST request to the specified URL with optional extra arguments.
5551
56-
This method is a thin wrapper around `requests.post()`. Any additional arguments
57-
are passed directly to `requests.post()`. For more information on the available
58-
arguments, refer to the `requests.post()` documentation:
52+
This method is a thin wrapper around `requests.post()`. Any additional arguments
53+
are passed directly to `requests.post()`. For more information on the available
54+
arguments, refer to the `requests.post()` documentation:
5955
https://docs.python-requests.org/en/latest/api/#requests.post
6056
6157
Args:
@@ -69,8 +65,8 @@ def post(self, url, *args, **kwargs):
6965
Raises:
7066
HTTPError: If the request fails for a network-related reason.
7167
"""
72-
return self._handle_request('POST', url, *args, **kwargs)
73-
68+
return self._handle_request("POST", url, *args, **kwargs)
69+
7470
# Method to handle requests for GET and POST
7571
def _handle_request(self, method, url, *args, **kwargs):
7672
logging.info(f"Sending {method} request to {url}")
@@ -80,8 +76,12 @@ def _handle_request(self, method, url, *args, **kwargs):
8076
return response
8177

8278
except HTTPError as http_err:
83-
logging.error(f"HTTP error occurred: {http_err} when sending a {method} to {url} with headers {kwargs.get('headers')}")
79+
logging.error(
80+
f"HTTP error occurred: {http_err} when sending a {method} to {url} with headers {kwargs.get('headers')}"
81+
)
8482
raise http_err
8583
except Exception as err:
86-
logging.error(f"Other error occurred: {err} when sending a {method} to {url} with headers {kwargs.get('headers')}")
84+
logging.error(
85+
f"Other error occurred: {err} when sending a {method} to {url} with headers {kwargs.get('headers')}"
86+
)
8787
raise err

dpytools/logger/logger.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
from typing import Dict, List, Optional, Union
2-
import structlog
3-
import traceback
41
import json
2+
import traceback
53
from datetime import datetime, timezone
4+
from typing import Dict, List, Optional
5+
6+
import structlog
67

78

89
def level_to_severity(level: int) -> int:

dpytools/slack/slack.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import logging
2+
23
from dpytools.http_clients.base import BaseHttpClient
34

4-
class SlackNotifier:
55

6+
class SlackNotifier:
67
def __init__(self, webhook_url):
78
if not webhook_url:
8-
raise ValueError('webhook_url is not set')
9+
raise ValueError("webhook_url is not set")
910
self.webhook_url = webhook_url
1011
self.http_client = BaseHttpClient()
1112

@@ -20,12 +21,12 @@ def notify(self, msg_dict: dict):
2021
response = self.http_client.post(self.webhook_url, json=msg_dict)
2122
response.raise_for_status()
2223
except Exception as e:
23-
logging.error(f'Failed to send notification: {e}')
24+
logging.error(f"Failed to send notification: {e}")
2425

2526
def msg_str(self, msg: str):
2627
"""
2728
Send a string message to the Slack webhook.
2829
2930
The msg parameter is wrapped into a dictionary before being sent.
3031
"""
31-
self.notify({'text': msg})
32+
self.notify({"text": msg})

dpytools/sns/sns.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
# See here: https://docs.aws.amazon.com/code-library/latest/ug/python_3_sns_code_examples.html
32
# Ideally we want to publish a message by passing in a dictionary.
43
# If SNS doesn not support that stringify any dict that is a message
@@ -12,20 +11,18 @@
1211

1312
from typing import Union
1413

14+
1515
# Note: return True if it works and False if we hit errors
1616
# (so we can control the flow in calling programs)
1717
def publish(topic: str, msg: Union[str, dict]) -> bool:
18-
"""
19-
20-
"""
18+
""" """
2119

2220

2321
# For this you'll want boto3 again, create a subscription
2422
# when the class is instantiated (error if you cant)
2523
# The get_message() needs to pull from the queue that's
2624
# been subscribed to.
2725
class Subscription:
28-
2926
def __init__(self, topic):
3027
"""
3128
subscrube to a topic (i.e setup to read messages)

0 commit comments

Comments
 (0)