move todays date inside route functions

This commit is contained in:
Sam 2024-08-27 15:37:27 +01:00
parent d851b03572
commit 5600889bb6
1 changed files with 96 additions and 47 deletions

View File

@ -8,116 +8,165 @@ import time
app = Flask(__name__) app = Flask(__name__)
CORS(app) CORS(app)
FILES_DIRECTORY = '../data/' FILES_DIRECTORY = "../data/"
today = datetime.datetime.today()
@app.before_request @app.before_request
def start_timer(): def start_timer():
g.start = time.time() g.start = time.time()
@app.after_request @app.after_request
def log(response): def log(response):
now = time.time() now = time.time()
duration = round(now - g.start, 4) duration = round(now - g.start, 4)
dt = datetime.datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S') dt = datetime.datetime.fromtimestamp(now).strftime("%Y-%m-%d %H:%M:%S")
log_entry = { log_entry = {
'timestamp': dt, "timestamp": dt,
'duration': duration, "duration": duration,
'method': request.method, "method": request.method,
'url': request.url, "url": request.url,
'status': response.status_code, "status": response.status_code,
'remote_addr': request.access_route[-1], "remote_addr": request.access_route[-1],
'user_agent': request.user_agent.string, "user_agent": request.user_agent.string,
} }
log_line = ','.join(f'{key}={value}' for key, value in log_entry.items()) log_line = ",".join(f"{key}={value}" for key, value in log_entry.items())
with open('api_logs.txt', 'a') as f: with open("api_logs.txt", "a") as f:
f.write(log_line + '\n') f.write(log_line + "\n")
return response return response
@app.route('/bitcoin_business_growth_by_country', methods=['GET'])
@app.route("/bitcoin_business_growth_by_country", methods=["GET"])
def business_growth(): def business_growth():
today = datetime.datetime.today()
# Parse args from request # Parse args from request
latest_date = request.args.get('latest_date') latest_date = request.args.get("latest_date")
country_names = request.args.get('countries') # change this line country_names = request.args.get("countries") # change this line
cumulative_period_type = request.args.get('cumulative_period_type') cumulative_period_type = request.args.get("cumulative_period_type")
# Open json locally # Open json locally
with open('../data/final__bitcoin_business_growth_by_country.json', 'rb') as f: with open("../data/final__bitcoin_business_growth_by_country.json", "rb") as f:
data = orjson.loads(f.read()) data = orjson.loads(f.read())
# Filter based on args # Filter based on args
if latest_date: if latest_date:
latest_date_bool = latest_date == 'true' latest_date_bool = latest_date == "true"
filtered_data = [item for item in data if item['latest_date'] == latest_date_bool] filtered_data = [
item for item in data if item["latest_date"] == latest_date_bool
]
else: else:
filtered_data = data filtered_data = data
if country_names: if country_names:
countries = [name.strip() for name in country_names.split(",")] countries = [name.strip() for name in country_names.split(",")]
filtered_data = [item for item in filtered_data if item['country_name'] in countries] filtered_data = [
item for item in filtered_data if item["country_name"] in countries
]
if cumulative_period_type == "1 day": if cumulative_period_type == "1 day":
delta = today - datetime.timedelta(days=2) delta = today - datetime.timedelta(days=2)
filtered_data = [item for item in filtered_data if item['cumulative_period_type'] == cumulative_period_type and delta <= datetime.datetime.strptime(item['date'], '%Y-%m-%d')] filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
elif cumulative_period_type == "7 day": elif cumulative_period_type == "7 day":
delta = today - datetime.timedelta(days=8) delta = today - datetime.timedelta(days=8)
filtered_data = [item for item in filtered_data if item['cumulative_period_type'] == cumulative_period_type and delta <= datetime.datetime.strptime(item['date'], '%Y-%m-%d')] filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
elif cumulative_period_type == "28 day": elif cumulative_period_type == "28 day":
delta = today - datetime.timedelta(days=29) delta = today - datetime.timedelta(days=29)
filtered_data = [item for item in filtered_data if item['cumulative_period_type'] == cumulative_period_type and delta <= datetime.datetime.strptime(item['date'], '%Y-%m-%d')] filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
elif cumulative_period_type == "365 day": elif cumulative_period_type == "365 day":
delta = today - datetime.timedelta(days=366) delta = today - datetime.timedelta(days=366)
filtered_data = [item for item in filtered_data if item['cumulative_period_type'] == cumulative_period_type and delta <= datetime.datetime.strptime(item['date'], '%Y-%m-%d')] filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
# Sort by date # Sort by date
sorted_data = sorted(filtered_data, key=lambda x: x['date'], reverse=False) sorted_data = sorted(filtered_data, key=lambda x: x["date"], reverse=False)
# Return json # Return json
return Response(json.dumps(sorted_data), mimetype='application/json') return Response(json.dumps(sorted_data), mimetype="application/json")
@app.route('/get_json/<filename>', methods=['GET'])
@app.route("/get_json/<filename>", methods=["GET"])
def get_json(filename): def get_json(filename):
period = request.args.get('period') period = request.args.get("period")
today = datetime.datetime.today()
file_path = os.path.join(FILES_DIRECTORY, filename) file_path = os.path.join(FILES_DIRECTORY, filename)
if not os.path.isfile(file_path): if not os.path.isfile(file_path):
abort(404) abort(404)
with open(file_path, 'r') as f: with open(file_path, "r") as f:
data = orjson.loads(f.read()) data = orjson.loads(f.read())
if period == "last 7 days": if period == "last 7 days":
delta = today - datetime.timedelta(days=7) delta = today - datetime.timedelta(days=7)
filtered_data = [item for item in data if delta <= datetime.datetime.strptime(item['date'], '%Y-%m-%d') <= today] filtered_data = [
sorted_data = sorted(filtered_data, key=lambda x: x['date']) item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
elif period == "last 28 days": elif period == "last 28 days":
delta = today - datetime.timedelta(days=28) delta = today - datetime.timedelta(days=28)
filtered_data = [item for item in data if delta <= datetime.datetime.strptime(item['date'], '%Y-%m-%d') <= today] filtered_data = [
sorted_data = sorted(filtered_data, key=lambda x: x['date']) item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
elif period == "last 365 days": elif period == "last 365 days":
delta = today - datetime.timedelta(days=365) delta = today - datetime.timedelta(days=365)
filtered_data = [item for item in data if delta <= datetime.datetime.strptime(item['date'], '%Y-%m-%d') <= today] filtered_data = [
sorted_data = sorted(filtered_data, key=lambda x: x['date']) item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
elif period == "last 2 years": elif period == "last 2 years":
delta = today - datetime.timedelta(days=730) delta = today - datetime.timedelta(days=730)
filtered_data = [item for item in data if delta <= datetime.datetime.strptime(item['date'], '%Y-%m-%d') <= today] filtered_data = [
sorted_data = sorted(filtered_data, key=lambda x: x['date']) item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
else: else:
sorted_data = sorted(data, key=lambda x: x['date']) sorted_data = sorted(data, key=lambda x: x["date"])
return jsonify(sorted_data) return jsonify(sorted_data)
@app.route('/download/<filename>', methods=['GET'])
@app.route("/download/<filename>", methods=["GET"])
def download_file(filename): def download_file(filename):
try: try:
return send_from_directory(FILES_DIRECTORY, filename, as_attachment=True) return send_from_directory(FILES_DIRECTORY, filename, as_attachment=True)
except FileNotFoundError: except FileNotFoundError:
abort(404) abort(404)
if __name__ == '__main__':
if __name__ == "__main__":
app.run() app.run()