Skip to content

Commit

Permalink
okay FINALLY passing request body properly - egg on face since I was …
Browse files Browse the repository at this point in the history
…reusing the same form submission for development, soooo no html changes were being propogated at all......
  • Loading branch information
GondekNP committed Jan 11, 2024
1 parent a07b387 commit 29eabac
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 66 deletions.
12 changes: 7 additions & 5 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,17 @@ def available_cogs(sftp_client: SFTPClient = Depends(get_sftp_client)):

# # create a POST endpoint for running a burn query with an input geojson, with its associated POST body class
class AnaylzeBurnPOSTBody(BaseModel):
geojson: dict
geojson: str
date_ranges: dict
fire_event_name: str
affiliation: str

@app.post("/api/analyze-burn")
def analyze_burn(body: AnaylzeBurnPOSTBody, sftp_client: SFTPClient = Depends(get_sftp_client)):
geojson = body.geojson
geojson = json.loads(body.geojson)
date_ranges = body.date_ranges
fire_event_name = body.fire_event_name
affiliation = body.affiliation
logger.log_text(f"Received analyze-burn request for {fire_event_name}")

try:
Expand All @@ -143,6 +145,7 @@ def analyze_burn(body: AnaylzeBurnPOSTBody, sftp_client: SFTPClient = Depends(ge
sftp_client.connect()
sftp_client.upload_fire_event(
metrics_stack=geo_client.metrics_stack,
affiliation=affiliation,
fire_event_name=fire_event_name,
prefire_date_range=date_ranges["prefire"],
postfire_date_range=date_ranges["postfire"]
Expand Down Expand Up @@ -213,17 +216,16 @@ async def upload_shapefile(fire_event_name: str = Form(...), affiliation: str =
with tempfile.NamedTemporaryFile(suffix=".geojson", delete=False) as tmp:
tmp_geojson = tmp.name
with open(tmp_geojson, "w") as f:
f.write(json.dumps(geojson))
f.write(geojson)
sftp_client.upload(
source_local_path=tmp_geojson,
remote_path=f"{affiliation}/{fire_event_name}/boundary.geojson"
)

sftp_client.disconnect()

remote_geojson_path = f"https://burn-severity-backend.s3.us-east-2.amazonaws.com/public/{affiliation}/{fire_event_name}/boundary.geojson"

return JSONResponse(status_code=200, content={"s3_geojson_url": remote_geojson_path})
return JSONResponse(status_code=200, content={"geojson": geojson})

except Exception as e:
return JSONResponse(status_code=400, content={"error": str(e)})
14 changes: 0 additions & 14 deletions src/static/map.html
Original file line number Diff line number Diff line change
Expand Up @@ -322,20 +322,6 @@
// Center map on fire, based on `bounds` metadata
map.fitBounds(fireBounds);

// Don't put the basemap over the metric layer, if it exists
// map.on('baselayerchange', function(eventLayer)
// {
// console.log(eventLayer.name);
// console.log(map.hasLayer(continiousTileLayer));
// if (map.hasLayer(continiousTileLayer)) {
// map.removeLayer(continiousTileLayer);
// continiousTileLayer.addTo(map);
// }
// if (map.hasLayer(classifiedTileLayer)) {
// map.removeLayer(classifiedTileLayer);
// classifiedTileLayer.addTo(map);
// }
// });
</script>

</body>
Expand Down
76 changes: 36 additions & 40 deletions src/static/upload.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,19 @@
</form>

<div id="upload-loading" style="display: none;">
<img src="spinner.gif" alt="Uploading shapefile... this may take a few moments." />
<img src="/static/spinner.gif" alt="Uploading shapefile... this may take a few moments." />
</div>

<div id="upload-success" style="display: none;">
<img src="checkmark.png" alt="Upload Success!" />
<img src="/static/checkmark.png" alt="Upload Success!" />
</div>

<div id="analysis-loading" style="display: none;">
<img src="spinner.gif" alt="Analyzing burn area... depending on AOI size, this may take several minutes." />
<img src="/static/spinner.gif" alt="Analyzing burn area... depending on AOI size, this may take several minutes." />
</div>

<div id="analysis-success" style="display: none;">
<img src="checkmark.png" alt="Analysis Success!" />
<img src="/static/checkmark.png" alt="Analysis Success!" />
</div>

<script>
Expand All @@ -53,48 +53,44 @@
formData.append('affiliation', $("#affiliation").val());

// Make a request to upload the shapefile
$.ajax({
var upload = $.ajax({
url: `/api/upload-shapefile-zip`,
type: 'post',
processData: false,
contentType: false,
data: formData,
success: function (data) {
// Hide the upload loading spinner and show the upload success checkmark
$("#upload-loading").hide();
$("#upload-success").show();
data: formData
});

$.when(upload).done(function(uploadResponse) {
// Log the data returned from the first AJAX call
console.log('upload success', uploadResponse);

// Make a request to analyze the burn
$.ajax({
url: '/api/analyze-burn',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
// Hide the analysis loading spinner and show the analysis success checkmark
$("#analysis-loading").hide();
$("#analysis-success").show();
},
error: function (error) {
// Handle error
console.error(error);
},
data: JSON.stringify({
fire_event_name: $("#fire_event_name").val(),
affiliation: $("#affiliation").val(),
date_ranges: {
prefire: [$("#prefire-start").val(), $("#prefire-end").val()],
postfire: [$("#postfire-start").val(), $("#postfire-end").val()]
}
})
});
},
error: function (error) {
// Handle error
console.error(error);
}
// Make a request to analyze the burn
$.ajax({
url: '/api/analyze-burn',
type: 'post',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({
geojson: uploadResponse.geojson,
fire_event_name: $("#fire_event_name").val(),
affiliation: $("#affiliation").val(),
date_ranges: {
prefire: [$("#prefire-start").val(), $("#prefire-end").val()],
postfire: [$("#postfire-start").val(), $("#postfire-end").val()]
}
}),
success: function (analysisResponse) {
console.log(analysisResponse);
},
error: function (error) {
console.error(error);
}
});
}).fail(function(error) {
console.error(error);
});
});
</script>
</script>
</body>
</html>
17 changes: 10 additions & 7 deletions src/util/sftp.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def update_available_cogs(self):
self.available_cogs = self.get_available_cogs()
self.disconnect()

def upload_cogs(self, metrics_stack, fire_event_name, prefire_date_range, postfire_date_range):
def upload_cogs(self, metrics_stack, fire_event_name, prefire_date_range, postfire_date_range, affiliation):

with tempfile.TemporaryDirectory() as tmpdir:

Expand All @@ -146,10 +146,10 @@ def upload_cogs(self, metrics_stack, fire_event_name, prefire_date_range, postfi

self.upload(
source_local_path=local_cog_path,
remote_path=f"{fire_event_name}/{band_name}.tif",
remote_path=f"{affiliation}/{fire_event_name}/{band_name}.tif",
)

def update_manifest(self, fire_event_name, bounds, prefire_date_range, postfire_date_range):
def update_manifest(self, fire_event_name, bounds, prefire_date_range, postfire_date_range, affiliation):
with tempfile.TemporaryDirectory() as tmpdir:

manifest = self.get_manifest()
Expand All @@ -162,7 +162,8 @@ def update_manifest(self, fire_event_name, bounds, prefire_date_range, postfire_
'bounds': bounds,
'prefire_date_range': prefire_date_range,
'postfire_date_range': postfire_date_range,
'last_updated': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'last_updated': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'requester_affiliation': affiliation
}

# Upload the manifest to our SFTP server
Expand All @@ -175,14 +176,15 @@ def update_manifest(self, fire_event_name, bounds, prefire_date_range, postfire_
)
self.logger.log_text(f"Uploaded/updated manifest.json")

def upload_fire_event(self, metrics_stack, fire_event_name, prefire_date_range, postfire_date_range):
def upload_fire_event(self, metrics_stack, fire_event_name, prefire_date_range, postfire_date_range, affiliation):
self.logger.log_text(f"Uploading fire event {fire_event_name}")

self.upload_cogs(
metrics_stack=metrics_stack,
fire_event_name=fire_event_name,
prefire_date_range=prefire_date_range,
postfire_date_range=postfire_date_range
postfire_date_range=postfire_date_range,
affiliation=affiliation
)

bounds = [round(pos, 4) for pos in metrics_stack.rio.bounds()]
Expand All @@ -191,7 +193,8 @@ def upload_fire_event(self, metrics_stack, fire_event_name, prefire_date_range,
fire_event_name=fire_event_name,
bounds=bounds,
prefire_date_range=prefire_date_range,
postfire_date_range=postfire_date_range
postfire_date_range=postfire_date_range,
affiliation=affiliation
)

def get_manifest(self):
Expand Down

0 comments on commit 29eabac

Please sign in to comment.