如何在 Odoo JSON 控制器中发送简单的消息和状态作为响应?

2023-11-30

我尝试了不同的方法来做到这一点,但它们不起作用。

首先我尝试了这种方式:

import openerp.http as http
from openerp.http import Response

class ResPartnerController(http.Controller):

    @http.route('/odoo/create_partner', type='json', auth='none')
    def index(self, **kwargs):

    Response.status = '400'
    return "Result message"

我在客户端中获得了正确的状态和消息。但如果我在 Odoo 界面上执行任何操作,我会收到这个奇怪的警告

enter image description here

有没有办法避免这个消息?

我也尝试过这两种方法:

data = {'result': 'RESULT message'}
json_data = json.dumps(data, encoding='utf-8')
headers = [('Content-Type', '{}; charset=utf-8'.format('application/json'))]
mimetype = 'application/json'
res = Response(
    response=json_data,
    status=status,
    headers=headers,
    mimetype=mimetype,
)
return res
msg = u'Response 200 badly built, falling back to a simple 200 OK response'
res = Response(msg, status=200)
return res

但我总是在客户端中收到此错误作为答案:

TypeError: <Response 9 bytes [400 BAD REQUEST]> is not JSON serializable\n", "message": "<Response 9 bytes [400 BAD REQUEST]> is not JSON serializable"

那么,是否有一种干净的方法来回答带有响应状态的简单消息?

发送回复状态对我来说也很重要

如果我只是回复一条消息,一切都会正常,但是如何在不出现奇怪行为的情况下更改状态?

顺便说一下,我使用这个脚本来进行调用

# -*- coding: utf-8 -*-

import requests
import json

url = 'http://localhost:8069/odoo/create_partner'
headers = {'Content-Type': 'application/json'}

data_res_partner = {
    'params': {
        'name': 'Example',
        'email': '[email protected]',
    }
}

data_json = json.dumps(data_res_partner)
response = requests.post(url=url, data=data_json, headers=headers)
print(response.status_code)
print(response.content)

Update

最后 @Phillip Stack 告诉我用 XML-RPC 来做到这一点,所以我写了这个其他问题为了澄清我的疑惑。


试试这个,我不确定我是否理解这里涉及的所有复杂性。尝试使用普通请求并将响应解析为 json 作为解决方法。如果我弄清楚 json 请求/响应我会更新它。我遇到了与您类似的问题,但能够让以下内容发挥作用。

尝试使用 http 类型

 @http.route('/test/test', auth='none', type='http')
 def test(self, **kwargs):
     return Response("TEST",content_type='text/html;charset=utf-8',status=500)

我的请求看起来像这样。

r = requests.post("http://localhost:8069/test/test",data={}))    
>>> r
<Response [500]>
>>> r.text
u'TEST'

尝试使用 json 类型

@http.route('/test/test', auth='none', type='json')
def test(self, **kwargs):
    Response.status = '400'
    return {'test':True}

使用这样构造的请求。

json_data = {"test": True}

requests.post("http://localhost:8069/test/test",data=json.dumps(json_data),headers={"Content-Type":"application/json"})

将上面的内容用于 python 请求。

使用下面的 JavaScript 示例

var json_data = { 'test': true };

$.ajax({ 
        type: "POST", 
        url: "/test/test", 
        async: false, 
        data: JSON.stringify(json_data), 
        contentType: "application/json", 
        complete: function (data) { 
            console.log(data);  
        } 
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Odoo JSON 控制器中发送简单的消息和状态作为响应? 的相关文章

随机推荐