python - 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) 我在哪里可以进一步调试这个问题?
感谢您在这里可能拥有的任何见解。
解决方案
你试过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 - 如何将 X_train、X_test、y_train、y_test 应用于特征重要性和返回质量指标?
- php - DataTables JQuery 给出警告,请求未知参数以响应来自单独的独立 AJAX 请求
- r - 堆叠的 ggplot2 geom_area 重新运行一个空图
- node.js - npm install 在 ansi-regex 安装 nodemon 的签名中出现错误
- python - 显示喜欢 django 帖子的用户
- javascript - 如何在简单的游戏中使用 javascript
- r - 将小提琴图与内部箱线图对齐的问题
- google-colaboratory - Google Colab 修订历史记录丢失
- python - 参数 newline='' 在 open 函数中有什么作用?
- ssl - HTTPS 信任链查询