Odoo V11集成RestAPI获取报表时报JSON序列化错误求助
解决Odoo V11 RestAPI获取报表时的JSON序列化错误
你遇到的是二进制数据无法JSON序列化的典型问题——render_qweb_pdf返回的result是PDF的字节流(bytes类型),而JSON格式并不支持直接序列化bytes对象,这就是触发TypeError的根源。下面是具体的解决步骤和修改方案:
问题分析
你的代码中,result是Odoo生成的PDF二进制数据,当你尝试把它放进self_reports字典并通过RestAPI返回时,JSON序列化器无法处理bytes类型,就会抛出"is not JSON serializable"的错误。
修复方案
我们需要把二进制的PDF数据转换成Base64编码的字符串(JSON支持字符串类型),这样就能正常序列化了。同时优化异常处理逻辑,确保错误信息也能正确返回。
修改后的generate_report方法代码如下:
import base64 import sys import odoo def generate_report(self, xml_id, ids): self_reports = {'result': False, 'state': False, 'exception': None} try: # 注意:render_qweb_pdf接受的是ids列表,确认你的ids参数是否已经是列表 # 如果ids是单个ID,用[int(ids)];如果已经是列表,直接传ids即可 result, report_format = request.env.ref(xml_id).sudo().render_qweb_pdf(ids if isinstance(ids, list) else [int(ids)]) if result: # 将二进制PDF转为Base64字符串 pdf_base64 = base64.b64encode(result).decode('utf-8') self_reports.update({ 'result': pdf_base64, 'state': True, 'format': report_format # 可选:返回报表格式(pdf/html等) }) else: self_reports['exception'] = "RML is not available at specified location or not enough data to print!" except Exception as e: # 捕获所有异常,将异常信息转为字符串,确保可JSON序列化 self_reports['exception'] = str(e) # 可选:打印堆栈信息用于调试 # import traceback # traceback.print_exc() return self_reports
关键改动说明
- Base64编码转换:用
base64.b64encode(result).decode('utf-8')把bytes类型的PDF数据转成字符串,这样JSON序列化器就能处理了。 - 参数校验:确认
ids参数的类型,render_qweb_pdf需要传入列表形式的ID,避免因参数格式错误导致的隐性问题。 - 异常处理优化:把异常对象转为字符串,避免因异常对象本身不可序列化导致的二次错误。
前端处理提示
前端拿到Base64字符串后,可以通过以下方式还原PDF:
- 创建一个Data URI:
data:application/pdf;base64,{你的Base64字符串} - 可以直接用这个URI打开新窗口显示PDF,或者下载保存。
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

