baseddata.io/backend/app.py

61 lines
1.9 KiB
Python
Raw Normal View History

from flask import Flask, jsonify, request, json, Response, send_from_directory, abort
2024-08-01 14:06:16 +01:00
from flask_cors import CORS
import orjson, os
2024-08-01 14:06:16 +01:00
app = Flask(__name__)
CORS(app)
FILES_DIRECTORY = '../data/'
2024-08-01 14:06:16 +01:00
@app.route('/bitcoin_business_growth_by_country', methods=['GET'])
def business_growth():
# Parse args from request
latest_date = request.args.get('latest_date')
country_names = request.args.get('countries') # change this line
cumulative_period_type = request.args.get('cumulative_period_type')
# Open json locally
with open('../data/final__bitcoin_business_growth_by_country.json', 'rb') as f:
data = orjson.loads(f.read())
# Filter based on args
if latest_date:
latest_date_bool = latest_date == 'true'
filtered_data = [item for item in data if item['latest_date'] == latest_date_bool]
else:
filtered_data = data
if country_names:
countries = [name.strip() for name in country_names.split(",")]
filtered_data = [item for item in filtered_data if item['country_name'] in countries]
if cumulative_period_type:
filtered_data = [item for item in filtered_data if item['cumulative_period_type'] == cumulative_period_type]
# Sort by date
sorted_data = sorted(filtered_data, key=lambda x: x['date'], reverse=True)
# Return json
return Response(json.dumps(sorted_data), mimetype='application/json')
@app.route('/get_json/<filename>', methods=['GET'])
def get_json(filename):
file_path = os.path.join(FILES_DIRECTORY, filename)
if not os.path.isfile(file_path):
abort(404)
2024-08-01 14:06:16 +01:00
with open(file_path, 'r') as file:
data = json.load(file)
2024-08-01 14:06:16 +01:00
return jsonify(data)
2024-08-01 14:06:16 +01:00
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
try:
return send_from_directory(FILES_DIRECTORY, filename, as_attachment=True)
except FileNotFoundError:
abort(404)
2024-08-01 14:06:16 +01:00
if __name__ == '__main__':
app.run()