Dynamically serving a matplotlib image to the web using python

后端 未结 6 1507
悲哀的现实
悲哀的现实 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:26

    My first question is: Does the image change often? Do you want to keep the older ones? If it's a real-time thing, then your quest for optimisation is justified. Otherwise, the benefits from generating the image on the fly aren't that significant.

    The code as it stands would require 2 requests:

    1. to get the html source you already have and
    2. to get the actual image

    Probably the simplest way (keeping the web requests to a minimum) is @Alex L's comment, which would allow you to do it in a single request, by building a HTML with the image embedded in it.

    Your code would be something like:

    # Build your matplotlib image in a iostring here
    # ......
    #
    
    # Initialise the base64 string
    #
    imgStr = "data:image/png;base64,"
    
    imgStr += base64.b64encode(mybuffer)
    
    print "Content-type: text/html\n"
    print """
    # ...a bunch of text and html here...
        
    #...more text and html...
        
    """ % imgStr
    

    This code will probably not work out of the box, but shows the idea.

    Note that this is a bad idea in general if your image doesn't really change too often or generating it takes a long time, because it will be generated every time.

    Another way would be to generate the original html. Loading it will trigger a request for the "test.png". You can serve that separately, either via the buffer streaming solution you already mention, or from a static file.

    Personally, I'd stick with a decoupled solution: generate the image by another process (making sure that there's always an image available) and use a very light thing to generate and serve the HTML.

    HTH,

提交回复
热议问题