The temporary file created by tempfile.NamedTemporaryFile on windows does not have permission to open PermissionError: [Errno 13] Permission denied

I encountered a rather cheating problem during the development process today. Record it here.

The usage scenario is like this, when we use odoo, we need to print a word document. The general approach is this.

Create a temporary file in the temporary folder, then add the temporary file, and then write the content of the template. Download it.

def _convert_binary_to_doc(self, file_template_data=None, suffix='docx'):
        fp = tempfile.NamedTemporaryFile(suffix='docx', dir="H:/T")
        print(fp)
        fp.close()
        if file_template_data == None:
            # print(self.file_template_data)
            fp.write(binascii.a2b_base64(self.file_template_data))
        else:
            fp.write(binascii.a2b_base64(file_template_data))
        fp.seek(0)
        return fp

In use

tempfile.NamedTemporaryFile found when opening a temporary file. The read and write permissions of the opened temporary file are wb+

But after coming out of the method, check the permissions of the file. It has indeed become read-only. As a result, my subsequent file writing operations cannot be performed.

Report permission error.

Odoo Server Error
Traceback (most recent call last):
  File "d:\nmgsys\odoo\lims\populating_ms_word_template\controllers\report_controller.py", line 78, in report_download
    response = self.report_routes(reportname, docids=docids, converter=converter)
  File "D:\NMGSYS\odoo\odoo\http.py", line 515, in response_wrap
    response = f(*args, **kw)
  File "d:\nmgsys\odoo\lims\populating_ms_word_template\controllers\report_controller.py", line 45, in report_routes
    docx = report.with_context(context).render_doc_doc(datas, data=data)[0]
  File "d:\nmgsys\odoo\lims\populating_ms_word_template\models\ir_actions_report.py", line 169, in render_doc_doc
    docx = self.export_doc_by_template(datas=res_ids[0], file_name_export=self.print_report_name,suffix=suffix)
  File "d:\nmgsys\odoo\lims\populating_ms_word_template\models\ir_actions_report.py", line 53, in export_doc_by_template
    shutil.copyfile(file_name, file_aa)
  File "c:\python36\lib\shutil.py", line 120, in copyfile
    with open(src, 'rb') as fsrc:
PermissionError: [Errno 13] Permission denied: 'H:\\T\\tmpi95ieb6tdocx'

I found relevant information on the Internet.

In the unix platform, we created a temporary file and can continue to open it again. But in windows, it cannot be opened again.

If it is used on the windows platform, temporary files cannot be created. You can create ordinary files directly, and delete them after the operation is completed.

Guess you like

Origin blog.csdn.net/u012798683/article/details/108750295