import os import io import time import json import flask import requests from dotenv import load_dotenv load_dotenv() # cache get_finances() for 5 minutes def get_finances(): return requests.get( url=f'{os.environ["CORE_API_URL"]}/finances', headers={ 'Authorization': f'{os.environ["CORE_API_KEY"]}' }, timeout=5 ).json() def register(app): @app.route('/finances') def finances_view(): try: data = get_finances() except Exception: return flask.Response('Error fetching finances from database. This might be cause the data is still being processed. Sorry.', status=500) finances = { 'last_update': data['timestamp'], 'donations_total': round(sum([i['amount_usd'] for i in data['donations']])), 'donations_num': len(data['donations']), 'donations_avg': round(sum([i['amount_usd'] for i in data['donations']]) / len(data['donations']), 2), 'donations_max': round(max([i['amount_usd'] for i in data['donations']])), 'most_used_donation_currency': max(data['donations'], key=lambda x: x['amount_usd'])['currency'], 'expenses_total': round(sum([i['amount_usd'] for i in data['expenses']])), 'expenses_wages': round(sum([i['amount_usd'] for i in data['expenses'] if i['type'] == 'wage'])), 'most_used_expense_currency': max(data['expenses'], key=lambda x: x['amount_usd'])['currency'], } return flask.render_template('finances.html', finances=finances) @app.route('/finances/json') def finances_download(): try: data = get_finances() except Exception: return flask.Response('Error fetching finances from database. This might be cause the data is still being processed. Sorry.', status=500) virtual_file = io.StringIO() json.dump(data, virtual_file, indent=4) name = f'finances-{time.strftime("%Y-%m-%d")}.json' virtual_file.seek(0) return flask.send_file( io.BytesIO(virtual_file.read().encode('utf-8')), mimetype='application/json', as_attachment=True, download_name=name )