Dynamically serving a matplotlib image to the web using python

后端 未结 6 1508
悲哀的现实
悲哀的现实 2020-11-29 02:43

This question has been asked in a similar way here but the answer was way over my head (I\'m super new to python and web development) so I\'m hoping there\'s a simpler way o

6条回答
  •  忘掉有多难
    2020-11-29 03:35

    You should

    • first write to a cStringIO object
    • then write the HTTP header
    • then write the content of the cStringIO to stdout

    Thus, if an error in savefig occured, you could still return something else, even another header. Some errors won't be recognized earlier, e.g., some problems with texts, too large image dimensions etc.

    You need to tell savefig where to write the output. You can do:

    format = "png"
    sio = cStringIO.StringIO()
    pyplot.savefig(sio, format=format)
    print "Content-Type: image/%s\n" % format
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) # Needed this on windows, IIS
    sys.stdout.write(sio.getvalue())
    

    If you want to embed the image into HTML:

    print "Content-Type: text/html\n"
    print """
    ...a bunch of text and html here...
    
    ...more text and html...
    """ % sio.getvalue().encode("base64").strip()
    

提交回复
热议问题