Debian Codegraph @

nsw_fuel/client.py

raw
1 import datetime
2 import requests
3 from typing import List, Optional, NamedTuple, Dict, Any
4
5 from .dto import (
6 Price, Station, Variance, AveragePrice, FuelCheckError,
7 GetReferenceDataResponse, GetFuelPricesResponse)
8
9 API_URL_BASE = 'https://api.onegov.nsw.gov.au/FuelCheckApp/v1/fuel'
10
11 PriceTrends = NamedTuple('PriceTrends', [
12 ('variances', List[Variance]),
13 ('average_prices', List[AveragePrice])
14 ])
15
16 StationPrice = NamedTuple('StationPrice', [
17 ('price', Price),
18 ('station', Station)
19 ])
20
21
22 class FuelCheckClient():
23 def __init__(self, timeout: Optional[int] = 10) -> None:
24 self._timeout = timeout
25
26 def _format_dt(self, dt: datetime.datetime) -> str:
27 return dt.strftime('%d/%m/%Y %H:%M:%S')
28
29 def _get_headers(self) -> Dict[str, Any]:
30 return {
31 'requesttimestamp': self._format_dt(datetime.datetime.now())
32 }
33
34 def get_fuel_prices(self) -> GetFuelPricesResponse:
35 """Fetches fuel prices for all stations."""
36 response = requests.get(
37 '{}/prices'.format(API_URL_BASE),
38 headers=self._get_headers(),
39 timeout=self._timeout,
40 )
41
42 if not response.ok:
43 raise FuelCheckError.create(response)
44
45 return GetFuelPricesResponse.deserialize(response.json())
46
47 def get_fuel_prices_for_station(
48 self,
49 station: int
50 ) -> List[Price]:
51 """Gets the fuel prices for a specific fuel station."""
52 response = requests.get(
53 '{}/prices/station/{}'.format(API_URL_BASE, station),
54 headers=self._get_headers(),
55 timeout=self._timeout,
56 )
57
58 if not response.ok:
59 raise FuelCheckError.create(response)
60
61 data = response.json()
62 return [Price.deserialize(data) for data in data['prices']]
63
64 def get_fuel_prices_within_radius(
65 self, latitude: float, longitude: float, radius: int,
66 fuel_type: str, brands: Optional[List[str]] = None
67 ) -> List[StationPrice]:
68 """Gets all the fuel prices within the specified radius."""
69
70 if brands is None:
71 brands = []
72 response = requests.post(
73 '{}/prices/nearby'.format(API_URL_BASE),
74 json={
75 'fueltype': fuel_type,
76 'latitude': latitude,
77 'longitude': longitude,
78 'radius': radius,
79 'brand': brands,
80 },
81 headers=self._get_headers(),
82 timeout=self._timeout,
83 )
84
85 if not response.ok:
86 raise FuelCheckError.create(response)
87
88 data = response.json()
89 stations = {
90 station['code']: Station.deserialize(station)
91 for station in data['stations']
92 }
93 station_prices = [] # type: List[StationPrice]
94 for serialized_price in data['prices']:
95 price = Price.deserialize(serialized_price)
96 station_prices.append(StationPrice(
97 price=price,
98 station=stations[price.station_code]
99 ))
100
101 return station_prices
102
103 def get_fuel_price_trends(self, latitude: float, longitude: float,
104 fuel_types: List[str]) -> PriceTrends:
105 """Gets the fuel price trends for the given location and fuel types."""
106 response = requests.post(
107 '{}/prices/trends/'.format(API_URL_BASE),
108 json={
109 'location': {
110 'latitude': latitude,
111 'longitude': longitude,
112 },
113 'fueltypes': [{'code': type} for type in fuel_types],
114 },
115 headers=self._get_headers(),
116 timeout=self._timeout,
117 )
118
119 if not response.ok:
120 raise FuelCheckError.create(response)
121
122 data = response.json()
123 return PriceTrends(
124 variances=[
125 Variance.deserialize(variance)
126 for variance in data['Variances']
127 ],
128 average_prices=[
129 AveragePrice.deserialize(avg_price)
130 for avg_price in data['AveragePrices']
131 ]
132 )
133
134 def get_reference_data(
135 self,
136 modified_since: Optional[datetime.datetime] = None
137 ) -> GetReferenceDataResponse:
138 """
139 Fetches API reference data.
140
141 :param modified_since: The response will be empty if no
142 changes have been made to the reference data since this
143 timestamp, otherwise all reference data will be returned.
144 """
145
146 if modified_since is None:
147 modified_since = datetime.datetime(year=2010, month=1, day=1)
148
149 response = requests.get(
150 '{}/lovs'.format(API_URL_BASE),
151 headers={
152 'if-modified-since': self._format_dt(modified_since),
153 **self._get_headers(),
154 },
155 timeout=self._timeout,
156 )
157
158 if not response.ok:
159 raise FuelCheckError.create(response)
160
161 # return response.text
162 return GetReferenceDataResponse.deserialize(response.json())