Day11 Let's ODOO: Controller

Controller是对URL endpoint处理,我们这里以两支API来做范例:

import json

from odoo import _
from odoo.http import Controller, Response, request, route, JsonRequest
from odoo.tools import date_utils

class StudtentController(Controller):
    
    @route('/student/all', methods=['GET'], type='http', auth='public', cors='*', csrf=False)
    def get_student_list(self):
        data = []
        students = request.env['res.student'].sudo().search([])
        for student in students:
            val = {
                'id': student.id,
                'name': student.name,
                'nickname': student.nickname,
                'gender': student.gender
            }
            data.append(val)
        result = {'data': data}
        body = json.dumps(result, default=date_utils.json_default)
        return Response(
            body, status=200,
            headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))]
        )   

    @route('/student', methods=['POST'], type='json', auth='public', cors='*', csrf=False)
    def create_student(self):
        student_data = json.loads(request.httprequest.data)
        val = {
            'name': student_data.get('name'),
            'nickname': student_data.get('nickname'),
            'gender': student_data.get('gender'),
            'birthday': student_data.get('birthday')
        }

        student_obj = request.env['res.student'].sudo()
        student_obj.create(val)
        result = {'code': 200, 'message': 'Created Successfully'}
        body = json.dumps(result, default=date_utils.json_default)
        return Response(
            body, status=200,
            headers=[('Content-Type', 'application/json'), ('Content-Length', len(body))]
        )

Route

@route 装饰器代表端点以及相关参数设定

第一个参数代表指定的endpoint,所以request url 就是 http://domain/student

methods:代表requests method,这里是阵列也可以写入多个requests method,透过ODOO内的request.httprequest.method 分辨後再做想要做的事,以第一只API为例我们只限定於GET method。

type: 只有jsonhttp两种,差别在於content type是不是application/json,来限制使用者请求,若不符规定则会返回错误。

auth: 有userpublicnone三种,user限定需要使用者在登入状态,常用在页面引导,而这边使用的API则是不需要经由登入认证故写为public

cors: 开通跨域的参数

crsf: 预设为True ,也就是crsf token认证,这边我们用API写法时要改为False

First API

我们第一只API用来查询学生资料,透过request.env['res.student'] ,寻找此model底下资料,因为我们在search内没有加上domain所以会找出所有资料,另外我们可以控制return给使用者的参数,这里只给id、名字、绰号、性别,性别是会给当初设定的Key值,最後要注意的是,返回的值必须为JSON Object。

HTTP method: GET

URL endpoint: /student/all

Response:

{
    "data": [
        {
            "id": 23,
            "name": "林小美",
            "nickname": "美美",
            "gender": "female"
        },
        {
            "id": 22,
            "name": "王大明",
            "nickname": false,
            "gender": "male"
        },
        {
            "id": 27,
            "name": "陈大熊",
            "nickname": "熊",
            "gender": "male"
        }
    ]
}

Second API

有前面的例子就很简单了,因我们之前设定birthday栏位为required ,所以新增的时候必须带入,我们透过create method,ODOO便会根据栏位新增。

HTTP method: POST

URL endpoint: /student

Request body:

{
	"name": "黄小华",
	"nickname": "阿华",
	"gender": "male",
	"birthday": "2020-02-01"
}

Response:

{
    "jsonrpc": "2.0",
    "id": null,
    "result": "<Response 48 bytes [200 OK]>"
}

Result:

https://ithelp.ithome.com.tw/upload/images/20210926/20130896UH5FgyGF1H.png
Controller的介绍就到这了,明天我们来介绍Security


<<:  [day14] 接收使用者的Line讯息

>>:  从零开始的8-bit迷宫探险【Level 18】为什麽他们开始乱跑?捉摸不定的怪物移动模式

【PHP Telegram Bot】Day05 - 程序语言的运作原理

众所皆知:「不会写程序的人都认为程序语言是写给电脑看的, 会写程序的人都知道程序语言是写给人看的。...

《Day30》MySQL Replication GTID

MySQL 从5.6.5开始支援GTID(global transaction identified...

【30天Lua重拾笔记34】番外篇: Fengari - 一个JS实现的Lua,运行Lua在浏览器内吧!

几年前关注过Moonshine和lua.vm.js,不过这两个项目貌似没什麽在更新了。Fengar...

Google Chrome v91 table colspan 异常

最新发布的Google Chrome v91 启用了 TableNG 造成我们网站部分功能跑版 这边...

[前端暴龙机,Vue2.x 进化 Vue3 ] Day11.列表渲染

当我们有很多重复的架构,内容却不一样,以旧有无框架的开发,我们可能就需要手动一笔一笔的刻出来,更进步...