Skip to content

Commit

Permalink
README updates for /register
Browse files Browse the repository at this point in the history
  • Loading branch information
sam-watttime committed Dec 22, 2023
1 parent 2b62e4a commit 7b9d973
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 4 deletions.
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# About
This SDK is meant to help users with basic queries to WattTime’s API (version 3), and to get data returned in specific formats (e.g., JSON, pandas, csv).

Users must first [register for access to the WattTime API here](https://watttime.org/docs-dev/data-plans/).
Users may register for access to the WattTime API through this client, however the basic user scoping given will only allow newly registered users to access data for the `CAISO_NORTH` region. Additionally, data may not be available for all signal types for newly registered users.

Full documentation of WattTime's API, along with response samples and information about [available endpoints is also available](https://docs.watttime.org/).

Expand All @@ -11,7 +11,16 @@ The SDK can be installed as a python package from the PyPi repository, we recomm
pip install watttime
```

Once registered for the WattTime API, you may set your credentials as environment variables to avoid passing these during class initialization:
If you are not registered for the WattTime API, you can do so using the SDK:
```
from watttime import WattTimeMyAccess
wt = WattTimeMyAccess(username=<USERNAME>, password=<PASSWORD>)
wt.register(email=<EMAIL>, organization=<ORGANIZATION>)
```

If you are already registered for the WattTime API, you may set your credentials as environment variables to avoid passing these during class initialization:
```
# linux or mac
export WATTTIME_USER=<your WattTime API username>
Expand Down
41 changes: 39 additions & 2 deletions tests/test_sdk.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import unittest
import unittest.mock as mock
from datetime import datetime, timedelta
from dateutil.parser import parse
from pytz import timezone, UTC
import os
from watttime import (
WattTimeBase,
WattTimeHistorical,
Expand All @@ -16,6 +18,30 @@
REGION = "CAISO_NORTH"


def mocked_register(*args, **kwargs):
url = args[0]

class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code

def json(self):
return self.json_data

if (
(url == "https://api.watttime.org/register")
& (kwargs["json"]["email"] == os.getenv("WATTTIME_EMAIL"))
& (kwargs["json"]["username"] == os.getenv("WATTTIME_USER"))
& (kwargs["json"]["password"] == os.getenv("WATTTIME_PASSWORD"))
):
return MockResponse(
{"ok": "User created", "user": kwargs["json"]["username"]}, 200
)
else:
raise MockResponse({"error": "Failed to create user"}, 400)


class TestWattTimeBase(unittest.TestCase):
def setUp(self):
self.base = WattTimeBase()
Expand Down Expand Up @@ -91,6 +117,12 @@ def test_parse_dates_with_datetime(self):
self.assertIsInstance(parsed_end, datetime)
self.assertEqual(parsed_end.tzinfo, UTC)

@mock.patch("requests.post", side_effect=mocked_register)
def test_mock_register(self, mock_post):
resp = self.base.register(email=os.getenv("WATTTIME_EMAIL"))
self.assertEqual(resp.status_code, 200)
self.assertEqual(len(mock_post.call_args_list), 1)


class TestWattTimeHistorical(unittest.TestCase):
def setUp(self):
Expand Down Expand Up @@ -154,16 +186,21 @@ def test_get_historical_pandas_meta(self):
self.assertIn("point_time", df.columns)
self.assertIn("value", df.columns)
self.assertIn("meta", df.columns)

def test_get_historical_csv(self):
start = parse("2022-01-01 00:00Z")
end = parse("2022-01-02 00:00Z")
self.historical.get_historical_csv(start, end, REGION)

fp = Path.home() / "watttime_historical_csvs" / f"{REGION}_co2_moer_{start.date()}_{end.date()}.csv"
fp = (
Path.home()
/ "watttime_historical_csvs"
/ f"{REGION}_co2_moer_{start.date()}_{end.date()}.csv"
)
assert fp.exists()
fp.unlink()


class TestWattTimeMyAccess(unittest.TestCase):
def setUp(self):
self.access = WattTimeMyAccess()
Expand Down
13 changes: 13 additions & 0 deletions watttime/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,19 @@ def _get_chunks(
# API response is inclusive, avoid overlap in chunks
chunks = [(s, e - timedelta(minutes=5)) for s, e in chunks[0:-1]] + [chunks[-1]]
return chunks

def register(self, email: str, organization: Optional[str] = None) -> requests.Response:
"""Register for the WattTime API, if you do not already have an account."""
url = f"{self.url_base}/register"
params = {
'username': self.username,
'password': self.password,
'email': email,
'org': organization,
}

rsp = requests.post(url, json=params, timeout=20)
return rsp


class WattTimeHistorical(WattTimeBase):
Expand Down

0 comments on commit 7b9d973

Please sign in to comment.