Can I write to a Media object as a file?

I have a library that generates images (qrcode) on the server that I would like to return to an app as Media objects. But the library only writes to files or BytesIO objects.

Can I get this into a Media object?

Good question. The best way to do this is to use an intermediate BytesIO objects to buffer the data. Something like this:

import anvil
from io import BytesIO

def write_media():
  data = BytesIO()

  # ... do something that writes to 'data' as a file here ...
  # For example:
  data.write("foo")

  # Now reset the stream so you can read from it:
  data.seek(0)

  return anvil.BlobMedia("text/plain", data.read(), name="my_file.txt")

Hope that helps!

That worked; thanks!

My server module ended up looking like this:

from anvil import *
import anvil.server
import qrcode
import qrcode.image.svg
from io import BytesIO

@anvil.server.callable
@anvil.server.http_endpoint("/qrcode")
def make_qr_code(qr_code_data, **params):
    qrcode_obj = qrcode.make(qr_code_data, image_factory=qrcode.image.svg.SvgPathImage)
    data = BytesIO()
    qrcode_obj.save(data)
    data.seek(0)
    return BlobMedia("image/svg+xml", data.read(), name="qrcode.svg")

and it generates SVG QR codes like a treat!

1 Like