posttrack/services/austrianpost.py

36 lines
1.3 KiB
Python

from services.base import PostalService
from request import Request
from status import Status
import urllib.request
import json
import datetime
API_URL = "https://api.post.at/sendungen/sv/graphqlPublic"
STATUS_REQUEST = "query { sendung(sendungsnummer: \"%s\") { sendungsnummer branchkey estimatedDelivery { startDate endDate startTime endTime } dimensions { height width length } status weight sendungsEvents { timestamp status reasontypecode text textEn eventpostalcode eventcountry } } }"
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
class AustrianPost(PostalService):
regex = [r"\d{22}"]
def get_data(self, trackingcode):
query = {"query": STATUS_REQUEST % trackingcode}
payload = json.dumps(query).encode("utf8")
req = Request(API_URL, data=payload, headers={"content-type": "application/json"})
res = urllib.request.urlopen(req)
return json.load(res)
def get_status(self, trackingcode):
data = self.get_data(trackingcode)
events = data["data"]["sendung"][0]["sendungsEvents"]
latest = events[-1]
timestamp = datetime.datetime.strptime(latest["timestamp"][:-3] + latest["timestamp"][-2:], DATE_FORMAT)
return Status(trackingcode, timestamp, latest["text"])
service = AustrianPost