首页 > 解决方案 > AWS Lambda、Python 和 Plotly:通过 plotly.offline.plot() 生成 SVG 似乎不起作用

问题描述

我正在尝试使用 plotly 的plot()方法从 AWS Lambda 输出 SVG。这在本地环境中有效,但在 Lambda 中似乎失败了。

代码块:

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!"

我对上面的代码的理解是,我没有写,首先创建一个带有可执行 JS 的 html,然后将 html 下载为 SVG,从而生成 SVG。我们尝试打开 html 文件下载 SVG,但必须等待并重试几次,以防需要时间。(如果你知道更好的方法,请告诉我。)

在线上print(os.listdir),您会注意到 html 存在,但要么 A) 未生成 SVG,要么 B) 如果生成了,它被 plotly 写入某个奇怪的目录。

问题:

1)如何控制plotly.offline.plot()将SVG写入的目录?

2) 默认情况下,它试图在 CentOS 上写入哪里?由于 Lambda 权限,它可能正在尝试写入但未能写入。

3) Lambda 上是否有/tmp/我可以检查的“下载”文件夹?

4) Lambda 可能无法导出 SVG 是否有其他原因 - 例如,无法打开 HTML 文件或无法加载嵌入式 JS。

5) 我在哪里可以进一步调试这个问题?

感谢您在这里可能拥有的任何见解。

标签: pythonaws-lambdaplotly

解决方案


你试过plotly.io.write_image吗?或者类似的东西fig.write_image("images/fig1.svg")

Plotly 文档在此处描述静态图像导出:https ://plot.ly/python/v3/offline/

基本上,将图形转换为图像字节,然后写入文件。

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')

推荐阅读