Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda, Python, and Plotly: Generating SVG via plotly.offline.plot() doesn't seem to work

I'm trying to output SVG from AWS Lambda using plotly's plot() method. This works in a local environment but seems to fail in Lambda.

The block of code:

downloadRootFolder = "/tmp/" # Lambda's write directory is /tmp. Other directories will deny access
aFilename = "py_chart_" + uuid.uuid1().hex

plotly.offline.plot(chart, 
    output_type = "file",
    filename = downloadRootFolder + aFilename + ".html", # /tmp/py_chart_UUID.html
    image_filename = downloadRootFolder + aFilename,     # /tmp/py_chart_UUID
    image = "svg", image_width = w, # defined earlier
    image_height = h)

myFilename = aFilename + ".svg"

svgText = "<svg>could not find the svg file!</svg>"

maxAttempts = 20
millisecsToWait = 250

print(os.listdir("/tmp/")) # output: ['py_chart_380ac7b4fcf411e9b6c0d273169078fd.html'] (no .svg file)

for c in range(0,maxAttempts):
    if os.path.exists(downloadRootFolder + myFilename):
        f = open(downloadRootFolder + myFilename,"r")
        svgText = f.read()
        f.close()
    else:
        time.sleep(millisecsToWait/1000)
        print("look for saved svg file attempt # " + str(c))
return(svgText) # returns "could not find the svg file!"

My understanding of the above code, which I did not write, is that plotly generates SVG by first creating an html with executable JS, which then downloads the html as SVG. We try to open the html file to download SVG, but have to wait and retry several times in case it is taking time. (If you know a better way to do it, please let me know.)

On the print(os.listdir) line, you'll notice the html exists, but either A) The SVG is not being generated, or B) if it is generated, it is written by plotly to some weird directory.

Questions:

1) How do I control the directory plotly.offline.plot() writes SVG to?

2) Where is it attempting to write to on CentOS by default? It's possible it is trying and failing to write there due to Lambda permissions.

3) Is there a "downloads" folder on Lambda outside of /tmp/ that I could check?

4) Is there some other reason Lambda may be failing to export the SVG - for example, unable to open HTML files or unable to loaded embedded JS.

5) Where could I look to further debug this problem?

Appreciate any insight you may have here.

like image 523
8t12c7081 Avatar asked Mar 10 '26 14:03

8t12c7081


1 Answers

Have you tried plotly.io.write_image? Or something like fig.write_image("images/fig1.svg")

The Plotly docs describe Static Image Export here: https://plot.ly/python/v3/offline/

Basically, convert a figure into image bytes then write to a file.

import plotly.io as pio

static_image_bytes = pio.to_image(fig, format='png')
pio.write_image(fig, file='plotly_static_image.png', format='png')
like image 149
Tyler Avatar answered Mar 12 '26 03:03

Tyler