1

I like to use matplotlib to exhibit science experiment result, and I want to storage those pictures to MongoDB.
Although I had read the matplotlib official document, I can't find any method to get a file-like object can easily storage into GridFS.
A viable solution is to save the figure to a png file, then upload this png file to GridFS. Is there any more succinct method?

HZ-VUW
  • 842
  • 9
  • 20

1 Answers1

1

I solved this problem.

def plot_fig(file_name):
    x = np.linspace(0, 10, 10)
    y = np.linspace(0, 10, 10)
    plt.plot(x, y)

    from io import BytesIO
    figfile = BytesIO()
    plt.savefig(figfile, format='png')

    fs = GridFS(db)
    try:
        f = fs.new_file(filename=file_name)
        f.write(figfile.getvalue())
    finally:
        f.close()
HZ-VUW
  • 842
  • 9
  • 20