Cannot Add_picture in Python docx from Anvil Database

Hello dear Forumers ! :grinning:

I am trying to add some picture to my docx file from Anvil database.

before I did:
in the Form
I added File Uploader - user can upload file
and by the Click is defined Variable
Variable_name =self.fileLoaderName.file
anvil.server.call(‘Function_name’, Variable_name)

In the DataBase:

Data_Base_name - Colomn name as Variable_name
and picture uploaded to the DataBase as ‘Picture.png’

In other Form which has Create Bottom:

List_name = app_tables.Data_Base_name.search(tables.order_by(“Colomn_1”))
Variable_name = List_auditinfo[0][‘Colomn name’]

In Server code:
document = Document()
my_image = document.add_picture(Variable_name ,width=Inches(1.2))

OUTPUT:
AttributeError: ‘LazyMedia’ object has no attribute ‘seek’

Problem is that PythonDocx cannot read a Media files from Anvil Data base

Thank you very much for your answers in advance !

What is the python package you are using to handle the docx?
Can you post a clone link?

I am no file handling expert but this error is because you are actually passing the document.add_picture() function a LazyMedia object rather than a file.

Does the function expect a file name, file path or object as an argument?

FYI to make code snippets more readable you can enclose blocks of code in tripple backtics ` to make it more readable.

For more reading on file handling check out the docs, this section will likely be helpful.

Thank you very much Rick,

Yes you are right - it expect a file - a file name
I my Python IDE Pycharm on local machine I put the file in the same directory as Python package and it works well.
But here in cloud Anvil I cannot read the uploaded to the Database Picture.png by `document.add_picture()’ function

And now I put this section before main code in Anvil Server :
@anvil.server.callable
def write_media_to_file(Filename):
with anvil.media.TempFile(Filename) as file_name:
return file_name

Modified main code - call function

my_image = document.add_picture(write_media_to_file(Filename) ,width=Inches(1.2))

and output is:
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/lm2fjqe9t8xp923jn9jtyq6at7e7la9i’

Actually it is making Temp file but cannot read it

That’s not how with works. When the with block exits, the resources allocated by with are gone (e.g. your file). You should do your add_picture call inside the with block:

  with anvil.media.TempFile(Filename) as file_name:
    my_image = document.add_picture(file_name ,width=Inches(1.2))

As @rickhurlbatt suggested, if you want specific help a clone link to an app that demonstrates the issue would help. That way people can play with it and make sure what they’re suggesting works for your case.

3 Likes

Thank you very much Jay - it is working now !

1 Like