在odoo的controller文件中,当类型为json时,如何更改json响应格式?

In odoo's controller file, how to change the json response format when the type is json?

请求头中的application/json和请求体中的json字符串 http请求,Odoo服务器收到请求,但是json return发给客户端的不是我想要的return.

这里多了两个key,jsonrpcidresult。keyresult对应的字典才是我真正想要的return给客户。

并且如果我将http.route中的type变量改为http而不是json,我将无法接收json格式的数据来自客户。

怎么办?谢谢大家!

我的Odoo版本是10,python版本是2.7.12

这是我的代码

controllers.py

from odoo.http import Controller,route
class API(Controller):
    @route('/v1/access_something',type='json',auth='none',csrf=False,methods=['GET'])
    def access_something(self,**kwargs):
        return {"a":1,"b":2}

测试接口 requests

import requests
re = requests.get('http://192.168.1.55:8069/v1/access_something',json={"c":1},headers={'Content-Type':'application/json'})
print(re.json())

re.json()中的数据

{
    "jsonrpc": "2.0",
    "id": null,
    "result": {
        "a": 1,
        "b": 2
    }
}

但是下面的结果才是我想要的

{
    "a": 1,
    "b": 2
}

我找到了解决这个问题的方法。

出现这个问题是因为源代码_json_response中有一个方法JsonRequest我们可以动态覆盖

为了不干扰别人使用原有的框架,我们可以在自己的decorator@http.route中使用kwargs传递自己的特定参数。我们通过判断装饰器是否有我们自己的参数来构造我们需要return给客户端的json字典。

这是我的代码controllers.py

from odoo.http import Controller,route,JsonRequest

def _json_response(self, result=None, error=None):
    lover = self.endpoint.routing.get('lover')
    if lover == 'chun':
        response = {}
        if error is not None:
            response['error'] = error
        if result is not None:
            response = result
    else:
        response = {
            'jsonrpc': '2.0',
            'id': self.jsonrequest.get('id')
        }
        if error is not None:
            response['error'] = error
        if result is not None:
            response['result'] = result

    if self.jsonp:
        # If we use jsonp, that's mean we are called from another host
        # Some browser (IE and Safari) do no allow third party cookies
        # We need then to manage http sessions manually.
        response['session_id'] = self.session.sid
        mime = 'application/javascript'
        body = "%s(%s);" % (self.jsonp, json.dumps(response),)
    else:
        mime = 'application/json'
        body = json.dumps(response)

    return Response(
        body, headers=[('Content-Type', mime),
                       ('Content-Length', len(body))])

setattr(JsonRequest,'_json_response',_json_response) #overwrite the method

class API(Controller):
    @route('/v1/access_something',type='json',auth='none',csrf=False,methods=['GET'],lover='chun')
    def access_something(self,**kwargs):
        return {"a":1,"b":2}

具体参数lover='chun'是我们judgment.In方法_json_response的基础,我们可以通过self.endpoint.routing.get('lover')

得到这个参数