diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e5a66bb..a77c59f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -9,9 +9,8 @@ before_script: - source venv/bin/activate - pip install -U pip - pip install . - - echo "[KeyDelivery]" > config.ini + - echo "[CarbonTracer]" > config.ini - echo "key = ${API_KEY}" >> config.ini - - echo "secret = ${API_SECRET}" >> config.ini test: stage: test diff --git a/LICENSE b/LICENSE index cad43dc..4eda2e8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2023 Kumi Mitterer +Copyright (c) 2023 Kumi Mitterer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index e5c44cd..1339b59 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,35 @@ -# KeyDelivery API Python Client +# CarbonTracer API Python Client -This is a Python client for the KeyDelivery API. It is a wrapper around the [KeyDelivery](https://kd100.com/) API, which allows you to track your shipments. - -It is not fully featured yet, but it is a good starting point. +This is a Python client for CarbonTracer. It is a wrapper around the [CarbonTracer](https://carbontracer.uni-graz.at/) REST API, which allows you to calculate CO2 equivalents for personal transport. ## Installation ```bash -pip install git+https://kumig.it/kumitterer/pykeydelivery +pip install git+https://kumig.it/kumitterer/pycarbontracer.git ``` ## Usage ```python -from keydelivery import KeyDelivery +from pycarbontracer import CarbonTracer -api = KeyDelivery("YOUR_API_KEY", "YOUR_API_SECRET") +# Create a new CarbonTracer instance -# Find carrier by shipment number +ct = CarbonTracer("YOUR_API_KEY") -carrier_options = api.detect_carrier("YOUR_SHIPMENT_NUMBER") +# Or use CarbonTracer.from_config() if you have a config.ini in the format of config.dist.ini -# Realtime tracking +# Calculate the CO2 equivalents for a train trip from Graz to Vienna -tracking = api.realtime("CARRIER_CODE", "YOUR_SHIPMENT_NUMBER") +result = ct.routing("train", "8010 Graz", "1010 Wien") + +# Print the result + +print(f"CO2 equivalents: {result["response"]["data"]["co2eq"]} {result["response"]["data"]["unitco2eq"]}") ``` +The `CarbonTracer` class also has methods for the `location`, `address` and `co2only` endpoints, as documented in the [CarbonTracer API documentation](https://carbontracer.uni-graz.at/api-doc). The documentation also includes information about the input and output parameters, so make sure to check it out. + ## License -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. \ No newline at end of file +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. diff --git a/config.dist.ini b/config.dist.ini index bac223f..452814a 100644 --- a/config.dist.ini +++ b/config.dist.ini @@ -1,3 +1,2 @@ -[KeyDelivery] +[CarbonTracer] key = api_key -secret = api_secret diff --git a/pyproject.toml b/pyproject.toml index 54ad196..edd4fea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,12 +3,12 @@ requires = ["hatchling"] build-backend = "hatchling.build" [project] -name = "pykeydelivery" +name = "pycarbontracer" version = "0.9.0" authors = [ - { name="Kumi Mitterer", email="pykeydelivery@kumi.email" }, + { name="Kumi Mitterer", email="pycarbontracer@kumi.email" }, ] -description = "Simple Python wrapper to fetch data from KeyDelivery (kd100.com)" +description = "Simple Python wrapper to fetch data from CarbonTracer (carbontracer.uni-graz.at)" readme = "README.md" license = { file="LICENSE" } requires-python = ">=3.10" @@ -19,5 +19,5 @@ classifiers = [ ] [project.urls] -"Homepage" = "https://kumig.it/kumitterer/pykeydelivery" -"Bug Tracker" = "https://kumig.it/kumitterer/pykeydelivery/issues" \ No newline at end of file +"Homepage" = "https://kumig.it/kumitterer/pycarbontracer" +"Bug Tracker" = "https://kumig.it/kumitterer/pycarbontracer/issues" \ No newline at end of file diff --git a/src/pykeydelivery/__init__.py b/src/pycarbontracer/__init__.py similarity index 100% rename from src/pykeydelivery/__init__.py rename to src/pycarbontracer/__init__.py diff --git a/src/pycarbontracer/classes/__init__.py b/src/pycarbontracer/classes/__init__.py new file mode 100644 index 0000000..908e84e --- /dev/null +++ b/src/pycarbontracer/classes/__init__.py @@ -0,0 +1,2 @@ +from .http import HTTPRequest +from .carbontracer import CarbonTracer \ No newline at end of file diff --git a/src/pycarbontracer/classes/carbontracer.py b/src/pycarbontracer/classes/carbontracer.py new file mode 100644 index 0000000..6296660 --- /dev/null +++ b/src/pycarbontracer/classes/carbontracer.py @@ -0,0 +1,114 @@ +from hashlib import md5 +from configparser import ConfigParser +from urllib.parse import urljoin, quote + +import json + +from .http import HTTPRequest + + +class CarbonTracer: + BASE_URL = "https://api.carbontracer.uni-graz.at/" + + def __init__(self, key: str, base_url: str = BASE_URL): + self.key = key + self.base_url = base_url + + @classmethod + def from_config(cls, config: ConfigParser | str, section: str = "CarbonTracer") -> "CarbonTracer": + if isinstance(config, str): + temp_config = ConfigParser() + temp_config.read(config) + config = temp_config + + key = config.get(section, "key") + base_url = config.get(section, "base_url", fallback=cls.BASE_URL) + + return cls(key, base_url) + + def get_request(self, endpoint: str, message: dict) -> HTTPRequest: + url = self.base_url + endpoint + + request = HTTPRequest(url) + + return request + + def location(self, location: str) -> dict: + """Request a location from a string. + + Args: + location (str): The location to request. + + Returns: + dict: The response from the server. + """ + + request = HTTPRequest(urljoin(self.base_url, "/".join(["location", self.key, quote(location)]))) + + return request.execute() + + def address(self, postalCode: str, city: str, street: str): + """Request an (Austrian) address from a postal code, city and street. + + Args: + postalCode (str): The postal code. + city (str): The city. + street (str): The street. + + Returns: + dict: The response from the server. + """ + + request = HTTPRequest(urljoin(self.base_url, "/".join(["address", self.key, postalCode, city, street]))) + + return request.execute() + + def routing(self, type: str, start: str, dest: str, waypoints: bool = False, bbox: bool = False, airports: bool = False): + """Make a routing request. + + Args: + type (str): The type of routing to request, e.g. "car" or "train". See API documentation for more information. + start (str): The start location as a string starting with ZIP code or lat,lon coordinates. + dest (str): The destination location as a string starting with ZIP code or lat,lon coordinates. + waypoints (bool, optional): Whether to include waypoints for map display in the response. Defaults to False. + bbox (bool, optional): Whether to include the bounding box for map display in the response. Defaults to False. + airports (bool, optional): For flights, calculate the route from the nearest airports to start and dest. Defaults to False. + + Returns: + dict: The response from the server. + """ + + url = urljoin(self.base_url, "/".join(["routing", self.key, type, quote(start), quote(dest)])) + + options = [] + + if waypoints: + options.append("waypoints") + + if bbox: + options.append("bbox") + + if airports: + options.append("airports") + + if options: + url = url + "/" + "options=" + ",".join(options) + + request = HTTPRequest(url) + + return request.execute() + + def co2only(self, type: str, distance_km: int): + """Only calculate the CO2 emissions for a given distance for a given transport type. + + Args: + type (str): The type of transport to calculate the CO2 emissions for, e.g. "car" or "train". See API documentation for more information. + distance_km (int): The distance in kilometers. + + Returns: + dict: The response from the server. + """ + + request = HTTPRequest(urljoin(self.base_url, "/".join(["co2only", self.key, type, str(distance_km)]))) + + return request.execute() \ No newline at end of file diff --git a/src/pykeydelivery/classes/http.py b/src/pycarbontracer/classes/http.py similarity index 61% rename from src/pykeydelivery/classes/http.py rename to src/pycarbontracer/classes/http.py index d1613df..9ab1e76 100644 --- a/src/pykeydelivery/classes/http.py +++ b/src/pycarbontracer/classes/http.py @@ -4,7 +4,7 @@ import json class HTTPRequest(Request): - USER_AGENT = "Mozilla/5.0 (compatible; PyKeyDelivery/dev; +https://kumig.it/kumitterer/pykeydelivery)" + USER_AGENT = "Mozilla/5.0 (compatible; PyCarbonTracer/dev; +https://kumig.it/kumitterer/pycarbontracer)" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -15,7 +15,3 @@ class HTTPRequest(Request): if load_json: response = json.loads(response) return response - - def add_json_payload(self, payload: dict): - self.add_header("Content-Type", "application/json") - self.data = json.dumps(payload).encode("utf-8") diff --git a/src/pykeydelivery/classes/__init__.py b/src/pykeydelivery/classes/__init__.py deleted file mode 100644 index ad5576c..0000000 --- a/src/pykeydelivery/classes/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .http import HTTPRequest -from .keydelivery import KeyDelivery \ No newline at end of file diff --git a/src/pykeydelivery/classes/keydelivery.py b/src/pykeydelivery/classes/keydelivery.py deleted file mode 100644 index 675ac52..0000000 --- a/src/pykeydelivery/classes/keydelivery.py +++ /dev/null @@ -1,61 +0,0 @@ -from hashlib import md5 -from configparser import ConfigParser - -import json - -from .http import HTTPRequest - - -class KeyDelivery: - BASE_URL = "https://www.kd100.com/api/v1/" - - def __init__(self, key: str, secret: str, base_url: str = BASE_URL): - self.key = key - self.secret = secret - self.base_url = base_url - - @classmethod - def from_config(cls, config: ConfigParser | str, section: str = "KeyDelivery") -> "KeyDelivery": - if isinstance(config, str): - temp_config = ConfigParser() - temp_config.read(config) - config = temp_config - - key = config.get(section, "key") - secret = config.get(section, "secret") - base_url = config.get(section, "base_url", fallback=cls.BASE_URL) - - return cls(key, secret, base_url) - - def get_signature(self, message: dict) -> str: - content = json.dumps(message) - data = (content + self.key + self.secret).encode("utf-8") - return md5(data).hexdigest().upper() - - def get_request(self, endpoint: str, message: dict) -> HTTPRequest: - url = self.base_url + endpoint - signature = self.get_signature(message) - - request = HTTPRequest(url) - request.add_json_payload(message) - request.add_header("API-Key", self.key) - request.add_header("signature", signature) - - return request - - def realtime(self, carrier: str, tracking_number: str) -> bytes: - message = { - "carrier_id": carrier, - "tracking_number": tracking_number, - } - - request = self.get_request("tracking/realtime", message) - return request.execute() - - def detect_carrier(self, tracking_number: str) -> bytes: - message = { - "tracking_number": tracking_number, - } - - request = self.get_request("carriers/detect", message) - return request.execute() diff --git a/test.py b/test.py index 280602e..850f8c8 100644 --- a/test.py +++ b/test.py @@ -3,7 +3,7 @@ from configparser import ConfigParser import json -from pykeydelivery import * +from pycarbontracer import * class TestHTTPRequest(TestCase): def test_http_request(self): @@ -11,28 +11,27 @@ class TestHTTPRequest(TestCase): response = http.execute() self.assertEqual(response["headers"]["User-Agent"], http.USER_AGENT) - def test_http_request_with_json_payload(self): - http = HTTPRequest("https://httpbin.org/post") - http.add_json_payload({"foo": "bar"}) - response = http.execute() - self.assertEqual(response["headers"]["User-Agent"], http.USER_AGENT) - self.assertEqual(response["headers"]["Content-Type"], "application/json") - self.assertEqual(response["json"]["foo"], "bar") - -class TestKeyDelivery(TestCase): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) +class TestCarbonTracer(TestCase): + def setUp(self): self.config = ConfigParser() self.config.read("config.ini") - self.keydelivery = KeyDelivery.from_config(self.config) + self.carbontracer = CarbonTracer.from_config(self.config) - def test_detect_carrier(self): - response = self.keydelivery.detect_carrier("483432314669") - self.assertEqual(response["code"], 200) + def test_carbontracer_location(self): + response = self.carbontracer.location("Graz") + self.assertEqual(response["response"]["data"]["country"], "AT") - def test_realtime(self): - response = self.keydelivery.realtime("gls", "483432314669") - self.assertEqual(response["code"], 200) - -if __name__ == "__main__": - main() \ No newline at end of file + def test_carbontracer_address(self): + response = self.carbontracer.address("8010", "Graz", "Gartengasse") + self.assertEqual(response["response"]["data"]["country"], "Austria") + + def test_carbontracer_routing(self): + response = self.carbontracer.routing("car", "8010 Graz", "1010 Wien", waypoints=True) + self.assertTrue("wayPoints" in response["response"]["data"]) + self.assertEqual(response["response"]["data"]["requestType"], "car") + self.assertEqual(response["response"]["data"]["startLocation"]["postalCode"], "8010") + + def test_carbontracer_co2only(self): + response = self.carbontracer.co2only("car", 100) + self.assertEqual(response["response"]["data"]["distance"], 100) + self.assertEqual(response["response"]["data"]["requestType"], "car") \ No newline at end of file