今天在开发过程中遇到了一个比较坑爹的问题。这里记录一下。
使用场景是这样,我们在使用odoo的时候,需要打印word文档。大致做法是这样。
在临时文件夹中创建一个临时文件,然后将临时文件,然后写入模板的内容。在下载下来。
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
在使用
tempfile.NamedTemporaryFile打开临时文件的时候,发现。打开的临时文件读写权限为wb+
但是从方法中出来后,在查看文件的权限。确变成了只读。导致我后续的写文件操作无法执行。
报权限错误。
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'
找网上找了相关的资料发现。
在unix平台中,我们创建了临时文件,还可以继续再次打开。但是在windows中,不可以再次打开。
如果是在windows平台使用,那么就不能创建临时文件。可以直接创建普通的文件,操作完成后,在进行删除即可。