pythonplotlycloudinary

Can save Plotly image to Cloudinary?


Is it possible to write a Plotly chart directly into Cloudanary without first saving to a file?

So Plotly is something like this.

fig.write_image("fig1.png")

I want to upload the fig straight into Cloudinary. Which is something like this.

cloudinary.uploader.upload("dog.mp4",
                   asset_folder="pets",
                   public_id="my_dog",
                   overwrite=True)

can the fig.write_image() go inside the uploader?

Possible? Not possible. Trying to skip writing it to disk due to permission issues.

Thanks.


Solution

  • All depends on if both functions allow to use file-like object instead of filename.
    It could allow to use io.Bytes() to create file in memory instead of file on disk.


    I didn't test it but documentation for Plotly write_image() suggests it can use writeable object instead of filename and it could allow to use file-like object

    Something similar to:

    import io
    
    file_object = io.BytesIO()
    
    fig.write_image(file_object, format='png')
    

    Documentation for upload() shows that it can use data_stream (byte array buffer)
    which can be file-like object

    file_object.seek(0)  # move to the beginning of file after writing ,
                         # to read from the beginning of data
    
    cloudinary.uploader.upload(file_object, ...)
    

    The same documentation also shows that it can send data converted to string base64 and it also could be used for this - but it would need more work.

    It would need to use io.BytesIO to write image in memory, and later read it as bytes file_object.getvaule() and convert to base64 using Python module base64.b64encode()

    import io
    import base64
    
    file_object = io.BytesIO()
    
    fig.write_image(file_object)
    
    #file_object.seek(0)
    #data_bytes = file_object.read()
    
    data_bytes = file_object.getvalue()  # it gets bytes from object without using `.seek()` and `.read()`
    
    data_base64 = base64.b64encode(data_bytes)
    
    text_base64 = data_base64.encode()
    
    text = "data:image/png;base64," + text_base64
    
    cloudinary.uploader.upload(text, ...)