Odoo 接口
Posted liangsha0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Odoo 接口相关的知识,希望对你有一定的参考价值。
1. 很多人还是习惯使用restful格式进行接口操作,但odoo已默认jsonrpc,所以需要专门写一个装饰器
def json_response(func): """返回去除封装的JSON""" @wraps(func) def decorate(*args, **kwargs): request.__raw_json = True if hasattr(request, ‘jsonrequest‘): kwargs.update(request.jsonrequest) ret = func(*args, **kwargs) mime = ‘application/json‘ body = json.dumps(ret, ensure_ascii=False, sort_keys=True) resp = Response( body, status=200, headers=[(‘Content-Type‘, mime), (‘Content-Length‘, len(body)), (‘Access-Control-Allow-Origin‘, ‘*‘)] ) return resp return decorate
# 在最外层加即可,不出意外,最内层也可,反正自由调位置吧! @json_response @http.route([‘/api/post/erp/productcenter/sync‘], type=‘json‘, auth=‘public‘, website=True, csrf=False, cors="*", methods=[‘POST‘]) def sync_product_info(self, **params):
2. 若接口使用者使用接口不频繁,完全无必要设session,因为odoo的session默认为一周;若数据保密性强,应每次访问都进行登录。
from odoo.addons.web.controllers.main import ensure_db ensure_db() uid = request.session.authenticate(request.session.db, str(params.get(‘user‘)), str(params.get(‘password‘))) # ensure_db() 保证有仅一个数据库 # request.session.db 返回数据库名字 # str(params.get(‘user‘)) 获取user值,视情况从不同位置获取,此为post请求,最终把全代码贴上 # uid 从数据库查找到账号密码所对的用户id,是一个id值,有2个目的:1检验是否登录成功,若密码账号错误,则uid为false 2因为调接口的用户不一定拥有查看某个表的权限,所以此uid可以作为赋予权限使用 product_count = request.env[‘xxx.product.center.update.interface‘].sudo(uid).search_count([])
3.接口最好考虑到各种报错,所以进行报错收集
4.参数解析
.@http.route([‘/api/erp/productcenter/count‘], type=‘http‘, auth=‘public‘, website=True, cors="*") # cors="*" 防跨域 # [‘/api/erp/productcenter/count‘] path不包括端口和ip # type=‘http‘ 分http和json等 # auth=‘public‘ 分none,user,auth,user只需能登录就算数
5.代码参考,多多交流
# -*- coding: utf-8 -*- import json import logging from odoo import http, _ from functools import wraps from odoo.http import request, Response from odoo.addons.web.controllers.main import ensure_db _logger = logging.getLogger(__name__) def json_response(func): """返回去除封装的JSON""" @wraps(func) def decorate(*args, **kwargs): request.__raw_json = True if hasattr(request, ‘jsonrequest‘): kwargs.update(request.jsonrequest) ret = func(*args, **kwargs) mime = ‘application/json‘ body = json.dumps(ret, ensure_ascii=False, sort_keys=True) resp = Response( body, status=200, headers=[(‘Content-Type‘, mime), (‘Content-Length‘, len(body)), (‘Access-Control-Allow-Origin‘, ‘*‘)] ) return resp return decorate class xxxProductCenterAPI(http.Controller): @json_response @http.route([‘/api/post/erp/productcenter/sync‘], type=‘json‘, auth=‘public‘, website=True, csrf=False, cors="*", methods=[‘POST‘]) def sync_product_info(self, **params): """ 产品中心产品数据同步接口 :param start_num: 要查找的数据起始条码 :param end_num: 要查找的数据终止条码 :return: 接口返回值 """ ensure_db() uid = request.session.authenticate(request.session.db, str(params.get(‘user‘)), str(params.get(‘password‘))) if uid: try: start_num = params.get(‘start_num‘, 0) end_num = params.get(‘end_num‘, 1000) product_count = request.env[‘xxxproduct.center.update.interface‘].sudo(uid).search_count([]) if int(start_num) < int(end_num) and product_count > start_num: product_objs = request.env[‘xxx.product.center.update.interface‘].sudo(uid).search([], limit=min(1000, end_num - start_num), offset=start_num, order=‘id DESC‘) product_obj_list = [] for product_obj in product_objs: data = { ‘operatorType‘: product_obj.operatorType } product_obj_list.append(data) code = 0 msg = ‘已返回%s条数据!‘%len(product_obj_list) result = product_obj_list else: code = -2 msg = ‘起始或终止页码输入有误!‘ result = ‘‘ except Exception, e: code = -3 msg = list(e)[0] result = ‘‘ response = { ‘code‘: code, ‘msg‘: msg, ‘result‘: result } else: response = { ‘code‘: 404, ‘msg‘: ‘用户名或密码错误‘, ‘result‘: ‘‘ } return response @http.route([‘/api/erp/productcenter/count‘], type=‘http‘, auth=‘public‘, website=True, cors="*") def product_count(self): # 返回总数据量 product_count = request.env[‘xxx.product.center.update.interface‘].sudo().search_count([]) response = { ‘code‘: 0, ‘result‘: product_count } return json.dumps(response)
以上是关于Odoo 接口的主要内容,如果未能解决你的问题,请参考以下文章
Odoo(OpenERP)开发实践:通过XML-RPC接口访问Odoo数据库