@@ -172,6 +172,83 @@ async def exchange_rates(request, date=None):
172
172
)
173
173
174
174
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
+
175
252
# api.ExchangeratesAPI.io
176
253
@app .route ("/" , methods = ["GET" ], host = "api.exchangeratesapi.io" )
177
254
async def index (request ):
0 commit comments