为 python 网络应用程序将绘图保存到内存而不是磁盘
Saving plots to memory rather than disk for python web app
我正在开发一个 FastAPI 应用程序,它使用 sci-kit 学习生成一些 SVG 文件,这些文件在上传到 AWS-S3 进行永久存储之前保存在本地。但是,一旦部署到 Heroku 上,我就意识到它不允许写入本地存储。
如何生成这些文件的示例:
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt
fig = plt.figure()
decision_tree = plot_tree(
pruned_clf_dt, # a decision tree made by sklearn
filled=True,
rounded=True,
class_names= classNames,
feature_names=X.columns)
fig.savefig("example.svg", bbox_inches='tight')
是否可以fig.savefig
(放入变量)将 SVG 保存在内存中或以某种方式将绘制的树作为 SVG 保存到 AWS-S3 中?
答案是肯定的,可以通过使用 StringIO,尽管 S3 要求对象采用类似字符串(?)的格式,例如:
import io
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt
fig = plt.figure()
decision_tree = plot_tree(
pruned_clf_dt,
filled=True,
rounded=True,
class_names= classNames,
feature_names=X.columns)
s = io.StringIO()
fig.savefig(s, format = 'svg', bbox_inches='tight')
svg = s.getvalue()
name = "filename.svg"
s3bucket.put_object(
Key=name,
Body=svg,
)
我正在开发一个 FastAPI 应用程序,它使用 sci-kit 学习生成一些 SVG 文件,这些文件在上传到 AWS-S3 进行永久存储之前保存在本地。但是,一旦部署到 Heroku 上,我就意识到它不允许写入本地存储。
如何生成这些文件的示例:
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt
fig = plt.figure()
decision_tree = plot_tree(
pruned_clf_dt, # a decision tree made by sklearn
filled=True,
rounded=True,
class_names= classNames,
feature_names=X.columns)
fig.savefig("example.svg", bbox_inches='tight')
是否可以fig.savefig
(放入变量)将 SVG 保存在内存中或以某种方式将绘制的树作为 SVG 保存到 AWS-S3 中?
答案是肯定的,可以通过使用 StringIO,尽管 S3 要求对象采用类似字符串(?)的格式,例如:
import io
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt
fig = plt.figure()
decision_tree = plot_tree(
pruned_clf_dt,
filled=True,
rounded=True,
class_names= classNames,
feature_names=X.columns)
s = io.StringIO()
fig.savefig(s, format = 'svg', bbox_inches='tight')
svg = s.getvalue()
name = "filename.svg"
s3bucket.put_object(
Key=name,
Body=svg,
)