Odoo's Web Controllers (2)

Steps for usage

1) Guide package

from odoo import httporfrom odoo.http import request

2) Class creation

class Yp32011(http.Controller):
	....

3) Function definition

GET

  • return string
    @http.route('/index', auth='public', methods=["GET"],csrf=False, cors='*')
    def index(self):
        return "Hello, world"
    
  • return json
    • without parameters
      @http.route('/projects', auth='public', methods=["GET"],csrf=False, cors='*')
      def projects(self):
          project_obj = http.request.env["yp32011.inspection_project"].sudo().search([])
          result = [{
                      "id": record.id,
                      "name": record.name,
                  }
                  for record in project_obj]
          return json.dumps(result)
      
      In SQL, it is equivalent to
      @http.route('/projects', auth='public', methods=["GET"],csrf=False, cors='*')
      def projects_SQL(self):
          http.request.env.cr.execute("select * from yp32011_inspection_project")
          result = http.request.env.cr.fetchall()
          result = [{
                      "id": record[0],
                      "name": record[1],
                  }
                  for record in result]
      	return json.dumps(result)
      
    • With parameters
      1) Get by setting keyword parameters
      @http.route('/projects/<int:project_id>', auth='public', methods=["GET"],csrf=False, cors='*')
      def projects(self,project_id=None):
          project_obj = http.request.env["yp32011.inspection_project"].sudo().search([('id','=',project_id)])
          ...
      
      2) Obtain by setting variable length parameter kwargs
      @http.route('/projects/<int:project_id>', auth='public', methods=["GET"],csrf=False, cors='*')
      def projects(self,**kwargs):
      	# kwargs是个字典
          project_id=kwargs.get('project_id') # 或 kwargs['project_id']
          project_obj = http.request.env["yp32011.inspection_project"].sudo().search([('id','=',project_id)])
           ...
      

POST

Parameters passed by apipost

{
	"params": {
		"data": {
			"name": "test2",
			"inspected_procedure":[1],
		}
	}
}

1) Obtain parameters through http.request.jsonrequest

@http.route('/project', auth='public', methods=["POST"], type="json",csrf=False, cors='*')
def create_project(self):
    param = http.request.jsonrequest['params']
    # param是个字典
    vals={
        'name':param['data']['name'],
        'inspected_procedure':param['data']['inspected_procedure']
    }
    print(vals)
    http.request.env["yp32011.inspection_project"].sudo().create(vals)
    result={
        "code":200,
        "message":"ok",
        "data":"新建项目成功"
    }
    return json.dumps(result,ensure_ascii=False)

2) Obtained by setting variable length parameter kwargs

@http.route('/project', auth='public', methods=["POST"], type="json",csrf=False, cors='*')
def create_project(self,**kwargs):
    vals={
        'name':kwargs['data']['name'], # 或 kwargs.get('data').get('name')
        'inspected_procedure':kwargs['data']['inspected_procedure']
    }
	......

PUT

1) Obtain the record ID to be modified by setting keyword parameters
2) Obtain the parameter content to be modified through http.request.jsonrequest

@http.route('/projects/<string:pk>', methods=["PUT"], type="json", auth='public', csrf=False, cors='*')
def update_project(self, pk=None):
    param = http.request.jsonrequest
    project_obj = http.request.env["yp32011.inspection_project"].sudo().search([("id", "=", pk)])
    if not project_obj:
        return json.dumps("not exists")
    project_obj.name = param['params']['data']["name"]
    result = [{
        "id": record.id,
        "name": record.name,
    }
        for record in project_obj]
    return json.dumps(result)

DELETE

Obtain the record ID to be deleted by setting keyword parameters

@http.route('/projects/<string:pk>', methods=["DELETE"],auth='public', csrf=False, cors='*')
def delete_project(self, pk=None):
    project_obj = http.request.env["yp32011.inspection_project"].sudo().search([("id", "=", pk)])
    if not project_obj:
        return json.dumps("not exists")
    project_obj.unlink()
    result={
        "code":200,
        "message":"ok",
        "data":"删除项目成功"
    }
    return json.dumps(result,ensure_ascii=False)

Usage summary

  • view search(domian)
     result = http.request.env['bim5d.quality_standard'].search( [
         ('project_budget','=',project_id),
         ('state','=','done')
     ])
    
  • Find the total number: search_count(domian)
    result = http.request.env["bim5d.quality_record"].sudo().search_count([])
    
  • Use SQL: cr.execute("sql statement", param)
     http.request.env.cr.execute("select count(*) from (select DISTINCT header,feedback from bim5d_problem_record) t")
     result = http.request.env.cr.fetchone()
    
  • Return to the xml template page
    return request.render("模块名.template_id", values)
    
  • return json dataset
    return json.dumps(values)
    

Note: domain is an expression, usually used to filter data records.

Commonly used function methods

  • create(dics): Insert a record in the data table and return a new object.

  • search(domain): Query the list of eligible objects and return the list of objects.

  • search(domain, limit=1): Query an object that meets the conditions and return an object.

  • search_read(domain, fields): Query the list of dictionaries that meet the conditions. Returns a list of dictionaries for the specified fields.

  • browse(id): Browse objects and their associated objects. return object.

  • browse([ids]): browse the list of objects and return the list of objects

  • browse(id).read(fields): browse objects and their associated objects, and return a dictionary

  • search(domain).read(fields): Returns a list of specified field values ​​for the recordset. return list of dictionaries

  • write(dics): Save one or several fields of one or several records. Returns a Boolean value, True

  • unlink: delete one or several records

  • default_get: Reset the default value of one or more fields

  • default_set: reset the default value of the field

Guess you like

Origin blog.csdn.net/weixin_44141284/article/details/130583293