【问题标题】:Saving plots to memory rather than disk for python web app将绘图保存到内存而不是 python web 应用程序的磁盘
【发布时间】:2021-06-08 19:03:57
【问题描述】:

我正在开发一个 FastAPI 应用程序,它使用 sci-kit learn 生成一些 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 中?

【问题讨论】:

    标签: python matplotlib amazon-s3 heroku fastapi


    【解决方案1】:

    答案是肯定的,使用 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,
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 2010-11-29
      相关资源
      最近更新 更多