zliang commited on
Commit
8b86a54
·
verified ·
1 Parent(s): 06731a0

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +13 -10
main.py CHANGED
@@ -1,14 +1,14 @@
1
- from fastapi import FastAPI, HTTPException, Request
2
  from argopy import DataFetcher
3
  import matplotlib.pyplot as plt
4
- import uuid
5
- import os
 
6
 
7
  app = FastAPI()
8
 
9
  @app.get("/plot_trajectory")
10
- def plot_trajectory(request: Request,
11
- lon_min: float, lon_max: float, lat_min: float, lat_max: float,
12
  depth_min: float, depth_max: float,
13
  date_start: str, date_end: str):
14
  try:
@@ -18,19 +18,22 @@ def plot_trajectory(request: Request,
18
  # Plotting
19
  plt.figure()
20
  f.plot('trajectory', add_legend=False)
21
-
22
- # Instead of saving the plot, construct the URL
23
- base_url = str(request.base_url)
 
 
 
24
  image_url = f"{base_url}plot_trajectory?lon_min={lon_min}&lon_max={lon_max}&lat_min={lat_min}&lat_max={lat_max}&depth_min={depth_min}&depth_max={depth_max}&date_start={date_start}&date_end={date_end}"
25
 
26
- plt.close()
27
 
28
  return {"image_url": image_url}
29
-
30
  except Exception as e:
31
  raise HTTPException(status_code=500, detail=str(e))
32
 
33
 
 
34
  if __name__ == "__main__":
35
  import uvicorn
36
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ from fastapi import FastAPI, HTTPException
2
  from argopy import DataFetcher
3
  import matplotlib.pyplot as plt
4
+ from fastapi.responses import StreamingResponse
5
+ import io
6
+
7
 
8
  app = FastAPI()
9
 
10
  @app.get("/plot_trajectory")
11
+ def plot_trajectory(lon_min: float, lon_max: float, lat_min: float, lat_max: float,
 
12
  depth_min: float, depth_max: float,
13
  date_start: str, date_end: str):
14
  try:
 
18
  # Plotting
19
  plt.figure()
20
  f.plot('trajectory', add_legend=False)
21
+ buf = io.BytesIO()
22
+ plt.savefig(buf, format='png')
23
+ buf.seek(0)
24
+ plt.close()
25
+ StreamingResponse(buf, media_type="image/png")
26
+
27
  image_url = f"{base_url}plot_trajectory?lon_min={lon_min}&lon_max={lon_max}&lat_min={lat_min}&lat_max={lat_max}&depth_min={depth_min}&depth_max={depth_max}&date_start={date_start}&date_end={date_end}"
28
 
 
29
 
30
  return {"image_url": image_url}
31
+
32
  except Exception as e:
33
  raise HTTPException(status_code=500, detail=str(e))
34
 
35
 
36
+
37
  if __name__ == "__main__":
38
  import uvicorn
39
  uvicorn.run(app, host="0.0.0.0", port=7860)