To generate buffer object with image, I ended up with a snippet like this on QGIS side:
# Open pre-prepared QGIS .qpt Composer file which consists of map image only
composition_path = 'path to qpt file'
with open(composition_path, 'rt') as f:
content = f.read()
doc = QDomDocument()
doc.setContent(content)
c = QgsLayout(QgsProject().instance())
c.loadFromTemplate(doc, QgsReadWriteContext())
# Get the map item from Composer and set it's extent
map_item = getLayoutItemById(c, 'map', QgsLayoutItemMap)
map_item.zoomToExtent(memory.extent())
map_item.refresh()
# Export PNG to a buffer of QBuffer type
exporter = QgsLayoutExporter(c)
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
image = exporter.renderPageToImage(0)
image.save(buffer, 'PNG')
buffer.seek(0)
# Send payload like this to the server
payload = {
...,
'map_image':base64.encodebytes(buffer.data()).decode('utf-8'),
...
}
This was not included in question, but if anyone wonders what can you do with the object, on the server side I would load it into PIL
image like this:
image_data = payload.get('map_image')
map_image = BytesIO()
PilImage.open(
BytesIO(image_data.decode('base64_codec'))
).save(map_image, format='PNG')
map_image.seek(0)
# now do whatever with the PIL object, like create a PDF where map is an element