Writing to a media object

Similar to Can I write to a Media object as a file?

I’m using OpenCV.VideoWriter to create video files and I’d like to do that within Anvil and store the result in a data table.

However, the constructor only takes a string representing a file name (in the previous question, the constructor also accepted a BytesIO instance, but I don’t have that option).

I’ve tried using anvil.media.TempFile, but that requires a media object instance in its own constructor and both BlobMedia and URLMedia require content in their own constructors.

Is there any way for me to this? Do I need to create my own subclass of anvil.Media or is there some other cunning trick?

(I know I can use a TempFile but I’d really rather avoid that if possible).

I created a class to solve this:

import attr
from tempfile import NamedTemporaryFile


@attr.s()
class TempFileMedia:
    file = attr.ib(init=False, default=NamedTemporaryFile())

    @property
    def name(self):
        return self.file.name

    @property
    def blob(self, content_type):
        with self.file.open("rb") as file:
            blob = BlobMedia(content_type=content_type, content=file.read())
        return blob

To use it, I create an instance and pass its name attribute to OpenCV. I can then use the blob attribute to update my app table.

1 Like