我正在尝试使用 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 下载来 plotly 生成 SVG。我们尝试打开 html 文件来下载 SVG,但必须等待并重试几次以防耗时。 (如果您知道更好的方法,请告诉我。)
在 print(os.listdir)
行上,您会注意到 html 存在,但是 A) 没有生成 SVG,或者 B) 如果生成了,它被写入通过 plotly 到一些奇怪的目录。
问题:
1) 如何控制 plotly.offline.plot()
将 SVG 写入的目录?
2) 在 CentOS 上,默认情况下它试图写入哪里?由于 Lambda 权限,它可能正在尝试写入但失败。
3) 在 /tmp/
之外的 Lambda 上是否有我可以检查的“下载”文件夹?
4) Lambda 可能无法导出 SVG 是否还有其他原因 - 例如,无法打开 HTML 文件或无法加载嵌入式 JS。
5) 我在哪里可以进一步调试这个问题?
感谢您在这里获得的任何见解。
最佳答案
您尝试过 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')
关于python - AWS Lambda、Python 和 Plotly : Generating SVG via plotly. offline.plot() 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58667885/