How to get JSON data in an Odoo controller?

左心房为你撑大大i 提交于 2019-12-20 02:08:33

问题


I am trying to send some JSON data to an Odoo controller, but when I send the request, I always get 404 as response.

This is the code of my controller:

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"}'

Now, I type the URL (http://localhost:8069/test/result) on the browser to check if it is available, and I get function index at 0x7f04a28>, /test/result: Function declared as capable of handling request of type 'json' but called with a request of type 'http'. This way I know that the controller is listening at that URL and is expecting JSON data.

So I open a Python console and type:

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

When I print r in the console, it returns <Response [404]>, and I cannot see any message in the log (I was expecting The controller is called.).

There is a similar question here, but it is not exactly the same case:

OpenERP @http.route('demo_json', type="json") URL not displaying JSON Data

Can anyone help me? What am I doing wrong?


回答1:


I have just solved the problem.

Firstly, as @techsavvy told, I had to modify the decorator, to write type='http' instead of type='json'.

And after that, the request from the console returned a 404 error because it did not know which database it was sending data to. In localhost:8069 I had more than one database. So I tried to have only one at that port. And that is, now it works great!

To manage that without removing any of the other databases, I have just modified the config file to change the parameter db_filter and put there a regular expression which only included my current database.




回答2:


I have just gone through your issue and I noticed that you have written JSON route which is call from javascript. if you want to call it from browser url hit then you have to define router with type="http" and auth="public" argument in route:

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


来源:https://stackoverflow.com/questions/35913866/how-to-get-json-data-in-an-odoo-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!