Skip to content

Commit 19fdf7a

Browse files
committed
add history endpoint for historic data
1 parent 85cbcaa commit 19fdf7a

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

exchangerates/app.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,83 @@ async def exchange_rates(request, date=None):
172172
)
173173

174174

175+
@app.route("/history", methods=["GET", "HEAD"])
176+
@app.route("/api/history", methods=["GET", "HEAD"])
177+
@cors()
178+
async def exchange_rates(request):
179+
if request.method == "HEAD":
180+
return json("")
181+
182+
if "start_at" in request.raw_args:
183+
try:
184+
start_at = datetime.strptime(request.raw_args["start_at"], "%Y-%m-%d")
185+
except ValueError as e:
186+
return json(
187+
{"error": "start_at parameter format", "exception": "{}".format(e)},
188+
status=400,
189+
)
190+
else:
191+
return json({"error": "missing start_at parameter"})
192+
193+
if "end_at" in request.raw_args:
194+
try:
195+
end_at = datetime.strptime(request.raw_args["end_at"], "%Y-%m-%d")
196+
except ValueError as e:
197+
return json(
198+
{"error": "end_at parameter format", "exception": "{}".format(e)},
199+
status=400,
200+
)
201+
else:
202+
return json({"error": "missing end_at parameter"})
203+
204+
exchange_rates = (
205+
await ExchangeRates.query.where(ExchangeRates.date >= start_at.date())
206+
.where(ExchangeRates.date <= end_at.date())
207+
.order_by(ExchangeRates.date.asc())
208+
.gino.all()
209+
)
210+
211+
base = "EUR"
212+
historic_rates = {}
213+
for er in exchange_rates:
214+
rates = er.rates
215+
216+
if "base" in request.raw_args and request.raw_args["base"] != "EUR":
217+
base = request.raw_args["base"]
218+
219+
if base in rates:
220+
base_rate = Decimal(rates[base])
221+
rates = {
222+
currency: Decimal(rate) / base_rate
223+
for currency, rate in rates.items()
224+
}
225+
rates["EUR"] = Decimal(1) / base_rate
226+
else:
227+
return json(
228+
{"error": "Base '{}' is not supported.".format(base)}, status=400
229+
)
230+
231+
# Symbols
232+
if "symbols" in request.args:
233+
symbols = list(
234+
itertools.chain.from_iterable(
235+
[symbol.split(",") for symbol in request.args["symbols"]]
236+
)
237+
)
238+
239+
if all(symbol in rates for symbol in symbols):
240+
rates = {symbol: rates[symbol] for symbol in symbols}
241+
else:
242+
return json(
243+
{"error": "Symbols '{}' are invalid.".format(",".join(symbols))},
244+
status=400,
245+
)
246+
247+
historic_rates[er.date] = rates
248+
249+
return json({"base": base, "start_at": start_at.date().isoformat(), "end_at": end_at.date().isoformat(), "rates": historic_rates})
250+
251+
175252
# api.ExchangeratesAPI.io
176253
@app.route("/", methods=["GET"], host="api.exchangeratesapi.io")
177254
async def index(request):

0 commit comments

Comments
 (0)