Add mangrove_data route to backend

This commit is contained in:
Sam 2024-09-10 09:12:52 +01:00
parent 9e8e3f27a5
commit 2233e8b865
1 changed files with 39 additions and 1 deletions

View File

@ -1,6 +1,7 @@
from flask import Flask, g, jsonify, request, json, Response, send_from_directory, abort from flask import Flask, g, jsonify, request, json, Response, send_from_directory, abort
from flask_cors import CORS from flask_cors import CORS
import orjson, os import orjson, os
import pandas as pd
import datetime import datetime
import time import time
@ -47,7 +48,7 @@ def business_growth():
# 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")
cumulative_period_type = request.args.get("cumulative_period_type") cumulative_period_type = request.args.get("cumulative_period_type")
# Open json locally # Open json locally
@ -160,6 +161,32 @@ def get_json(filename):
return jsonify(sorted_data) return jsonify(sorted_data)
@app.route("/mangrove_data/<method>", methods=["GET"])
def mangrove_data(method):
with open("../data/dev/final__wdpa_pid_mangrove_diff_stats.json", "rb") as f:
data = orjson.loads(f.read())
if method == "countries":
df = pd.read_json(json.dumps(data))
countries = df[["year", "country", "n_pixels", "diff", "cumulative_diff"]]
countriesAgg = countries.groupby(["year", "country"]).agg(
{"n_pixels": "sum", "diff": "sum", "cumulative_diff": "sum"}
)
countriesAgg["year0_pixels"] = (
countriesAgg["n_pixels"] - countriesAgg["cumulative_diff"]
)
countriesAgg["pct_diff"] = (
100
* (countriesAgg["n_pixels"] - countriesAgg["year0_pixels"])
/ countriesAgg["year0_pixels"]
).round(2)
countriesLatest = countriesAgg.loc[[2020]].reset_index().set_index("country")
return Response(
countriesLatest.to_json(orient="index"), mimetype="application/json"
)
@app.route("/download/<filename>", methods=["GET"]) @app.route("/download/<filename>", methods=["GET"])
def download_file(filename): def download_file(filename):
try: try:
@ -168,5 +195,16 @@ def download_file(filename):
abort(404) abort(404)
@app.route("/cog", methods=["GET"])
def serve_cog():
year = request.args.get("year")
pid = request.args.get("pid") # change this line
dir = f"{FILES_DIRECTORY}/cog/{year}/"
try:
return send_from_directory(dir, f"{pid}.tif", as_attachment=True)
except FileNotFoundError:
abort(404)
if __name__ == "__main__": if __name__ == "__main__":
app.run() app.run()