odoo附件接口

372 阅读2分钟

新加附件预览下载接口:解决预览图片可能存在未登陆图片看不到问题:

	import base64

	import os

	import odoo

	from odoo import http

	from odoo.http import request

	from odoo.tools import image_process

	import mimetypes

	 

	ModuleBasedir=os.path.dirname(os.path.dirname(__file__))

	 

	'''文件存储:附件、图片'''

	 

	class PicUrl(http.Controller):

	 

	 

	    @http.route('/ad/image/<int:id>-<string:unique>', type='http', auth="public",crsf=False,cors="*")

	    def common_ad_image(self, xmlid=None, model='ir.attachment', id=None, field='datas',

	                                  filename_field='name', unique=None, filename=None, mimetype=None,

	                                  download=None, width=0, height=0, crop=False, access_token=None,

	                                  **kwargs):

	        '''

	        图片路由地址:

	        预览图片可能存在未登陆图片看不到问题:

	        '''

	        if len(unique) < 40:

	            return ''

	        # other kwargs are ignored on purpose

	        return self._common_ad_image(xmlid=xmlid, model=model, id=id, field=field,

	                                               filename_field=filename_field, unique=unique, filename=filename,

	                                               mimetype=mimetype,

	                                               download=download, width=width, height=height, crop=crop,

	                                               quality=int(kwargs.get('quality', 0)), access_token=access_token)

	 

	    def _common_ad_image(self, xmlid=None, model='ir.attachment', id=None, field='datas',

	                                   filename_field='name', unique=None, filename=None, mimetype=None,

	                                   download=None, width=0, height=0, crop=False, quality=0, access_token=None,

	                                   placeholder='placeholder.png', **kwargs):

	        status, headers, image_base64 = request.env['ir.http'].sudo().binary_content(

	            xmlid=xmlid, model=model, id=id, field=field, unique=unique, filename=filename,

	            filename_field=filename_field, download=download, mimetype=mimetype,

	            default_mimetype='image/png', access_token=access_token)

	        if status in [301, 304] or (status != 200 and download):

	            return request.env['ir.http']._response_by_status(status, headers, image_base64)

	        if not image_base64:

	            # Since we set a placeholder for any missing image, the status must be 200. In case one

	            # wants to configure a specific 404 page (e.g. though nginx), a 404 status will cause

	            # troubles.

	            status = 200

	            image_base64 = base64.b64encode(self.placeholder(image=placeholder))

	            if not (width or height):

	                width, height = odoo.tools.image_guess_size_from_field_name(field)

	 

	        image_base64 = image_process(image_base64, size=(int(width), int(height)), crop=crop, quality=int(quality))

	 

	        content = base64.b64decode(image_base64)

	        headers = http.set_safe_image_headers(headers, content)

	        response = request.make_response(content, headers)

	        response.status_code = status

	        return response

	 

	    @http.route(['/ad/content/<int:id>-<string:unique>'], type='http', auth="public")

	    def ad_content_common(self, xmlid=None, model='ir.attachment', id=None, field='datas',

	                          filename=None, filename_field='name', unique=None, mimetype=None,

	                          download=None, data=None, token=None, access_token=None, **kw):

	        if len(unique) < 40:

	            return ''

	        status, headers, content = request.env['ir.http'].sudo().binary_content(

	            xmlid=xmlid, model=model, id=id, field=field, unique=unique, filename=filename,

	            filename_field=filename_field, download=download, mimetype=mimetype, access_token=access_token)

	 

	        if status != 200:

	            return request.env['ir.http']._response_by_status(status, headers, content)

	        else:

	            content_base64 = base64.b64decode(content)

	            headers.append(('Content-Length', len(content_base64)))

	            response = request.make_response(content_base64, headers)

	        if token:

	            response.set_cookie('fileToken', token)

	        return response

原生的 pdf 打印,通过后端调用生成 pdf 后,生成附件,提供接口传送

  1. 下载 pdf 接口:直接返回的是一个文件对象,可直接下载
	from odoo import api, fields, models, _, SUPERUSER_ID

	import base64

	import logging

	import io

	_logger = logging.getLogger(__name__)

	 

	 

	@http.route('/fmcg/download/pdf', type='http', auth="public", csrf=False, cors='*')

	def upload_download_pdf(self, **kw):

	   """下载pdf接口:直接返回的是一个文件对象,可直接下载"""

	   report = request.env.ref('zimo_fmcg_app.action_inventory_report').with_user(SUPERUSER_ID)._render_qweb_pdf(1)

	   

	   #根据场景需要:直接附件表里获取的内容 待启用

	   # pdf_doc = request.env['ir.attachment'].sudo().search([('id', '=', 726)], limit=1)

	   # data = io.BytesIO(base64.standard_b64decode(pdf_doc.datas))

	  

	   #直接生成的流文件

	   data = io.BytesIO(report[0])

	   return http.send_file(data, filename='melon_inv.pdf', as_attachment=True)
  1. 返回一个 JSON 格式字符串,提供附件下载地址
	from odoo import api, fields, models, _, SUPERUSER_ID

	import base64

	import logging

	import io

	_logger = logging.getLogger(__name__)

	 

	@http.route('/fmcg/download/pdf2', type='json', methods=['POST'], auth="public", csrf=False, cors='*')

	def upload_download_pdf2(self, **kw):

	   """下载pdf接口"""

	   data = request.jsonrequest

	   print ('-----data-----',data)

	   report = request.env.ref('zimo_fmcg_app.action_inventory_report').with_user(SUPERUSER_ID)._render_qweb_pdf(1)

	   filename = 'test' + '.pdf'

	   attachment = request.env['ir.attachment'].sudo().create({

	       'name': filename,

	       'type': 'binary',

	       'datas': base64.b64encode(report[0]),

	       'res_model': 'zimo.store.inventory',

	       'res_id': 1,

	       'mimetype': 'application/x-pdf'

	   })

	   return json.dumps(

	       {"data": [{"pdf_file": "https://www.hxmelon.com/ad/content/%s-%s" % (attachment.id, attachment.checksum)}],

	        "result": "success"})

odoo 端接收附件接口

  1. 接收的是一个文件对象,需要去读内容

    base64_data = base64.b64encode(kw['file'].read())
    在这里插入图片描述

	import base64

	import logging

	import io

	_logger = logging.getLogger(__name__)

	 

	@http.route('/fmcg/active/image', type='http', methods=['POST'], auth="public", csrf=False, cors='*')

	def upload_active_imaget(self, **kw):

	    """上传图片接口"""

	    file = request.httprequest.data

	    _logger.info("-----------/fmcg/active/image--------------------------:%s", kw['file'])

	    if not kw['file']:

	        return json.dumps({'result': 'success', 'message': 'no image'})

	    # base64_data = base64.b64encode(kw['image_file'].read())

	    # base64_data = False

	    base64_data = base64.b64encode(kw['file'].read())

	    active_obj = request.env['zimo.store.activities'].sudo()

	    s_id = active_obj.search([('name', '=', kw['sid'])], limit=1)

	    if not s_id:

	        return json.dumps({'result': 'fail', 'message': 'not find record'})

	    attachment = request.env['ir.attachment'].sudo().create({

	        'name': kw['file'].filename,

	        'datas': base64_data,

	        'res_id': s_id.id,

	        'res_model': 'zimo.store.activities',

	    })

	    s_id.write({'attach_ids': [(6, 0, [attachment.id])]})

	    return json.dumps({'result': 'success', 'message': 'success'})
  1. 接收的是一个文件内容,直接转 base64,然后赋值
    file = request.httprequest.data
    base64_data = base64.b64encode(file)
    在这里插入图片描述
	import base64

	import logging

	import io

	_logger = logging.getLogger(__name__)

	 

	 

	@http.route('/fmcg/upload/image2', type='http', methods=['POST'], auth="public", csrf=False, cors='*')

	def upload_fmcg_imaget2(self, **kw):

	    file = request.httprequest.data

	    base64_data = base64.b64encode(file)

	    store_obj = request.env['zimo.store.management'].sudo()

	    s_id = store_obj.search([('code', '=', kw['sid'])], limit=1)

	    if not s_id:

	        return json.dumps({'result': 'fail', 'message': 'not find record'})

	    s_id.write({'image_1920': base64_data})

	    return json.dumps({'result': 'success', 'message': 'success'})