pythonflaskmapnik

Mapnik to Flask


I am trying to dynamically generate Mapnik renderings in a Flask app and return the image. I get it to work like this:

from io import BytesIO
from flask import Flask, send_file
import mapnik

app = Flask(__name__)

@app.route("/")
def serve_image():
    image = mapnik.Image(600, 300)
    mp = mapnik.Map(600, 300)
    mp.background = mapnik.Color('steelblue')
    mapnik.render(mp, image)
    # I would like to avoid the next two lines
    image.save('test.png', 'png')
    with open('test.png') as new_image:
        ret = BytesIO(new_image.read())
    return send_file(ret, mimetype='image/png')

Notes: I am saving the file to disk (done in the inner C++ works of Mapnik) and (Python) reading it back from disk. I cannot figure out how to get the Mapnik image into a Python file buffer in a more direct manner.

Hints: I mostly tried to use the Mapnik.Image.tostring method but without success. I am using the older Python 2.7 bindings because of the pain to install them in Python 3.


Solution

  • I found this solution

    from flask import Flask, Response
    import mapnik
    
    app = Flask(__name__)
    
    @app.route("/")
    def serve_image():
        image = mapnik.Image(600, 300)
        mp = mapnik.Map(600, 300)
        mp.background = mapnik.Color('steelblue')
        mapnik.render(mp, image)
        return Response(image.tostring('png'), mimetype='img/png')
    

    But it seems slower in the context of my application