如何在 Odoo 控制器中获取 JSON 数据?

How to get JSON data in an Odoo controller?

我正在尝试向 Odoo 控制器发送一些 JSON 数据,但是当我发送请求时,我总是收到 404 作为响应。

这是我的控制器的代码:

import openerp.http as http
import logging
_logger = logging.getLogger(__name__)

class Controller(http.Controller):

    @http.route('/test/result', type='json', auth='public')
    def index(self, **args):
        _logger.info('The controller is called.')
        return '{"response": "OK"}'

现在,我在浏览器中输入 URL (http://localhost:8069/test/result) 来检查它是否可用,然后我得到 function index at 0x7f04a28>, /test/result: Function declared as capable of handling request of type 'json' but called with a request of type 'http' .这样我就知道控制器正在监听 URL 并期待 JSON 数据。

所以我打开 Python 控制台并输入:

import json
import requests
data = {'test': 'Hello'}
data_json = json.dumps(data)
r = requests.get('http://localhost:8069/test/result', data=data_json)

当我在控制台打印 r 时,它 returns ,我看不到日志中的任何消息(我期待 控制器被调用。)。

这里也有类似的问题,但不是完全一样的情况:

谁能帮帮我?我做错了什么?

我刚刚解决了你的问题,我注意到你写了 JSON 路由,它是从 javascript 调用的。如果你想从浏览器调用它 url hit 那么你必须在路由中使用 type="http"auth="public" 参数定义路由器:

@http.route('/', type='http', auth="public", website=True)

我刚刚解决了这个问题。

首先,正如@techsavvy 所说,我不得不修改装饰器,写成 type='http' 而不是 type='json'

然后,控制台的请求返回了 404 错误,因为它不知道将数据发送到哪个数据库。在 localhost:8069 我有不止一个数据库。所以我试着在那个港口只有一个。也就是说,现在效果很好!

为了在不删除任何其他数据库的情况下进行管理,我刚刚修改了配置文件以更改参数 db_filter 并在其中放置了一个仅包含我当前数据库的正则表达式。