Xodoo第十六节

Controller

 一般通过继承的形式来创建controller类,继承http.Controller

默认配置在controllers包中。在__init__.py文件下引入controllers包。

from odoo import http
from odoo.http import request


class Main(http.Controller):

    @http.route('/my_hostel/students', type='http', auth='none')
    def students(self):
        students = request.env['hostel.student'].sudo().search([])
        html_result = '<html><body><ul>'
        for student in students:
            html_result += "<li> %s </li>" % student.name
        html_result += '</ul></body></html>'
        return html_result
    

路由设置

http.route(route=None, **kw) 装饰器可以将对应方法装饰为处理对应的http请求 

route:字符串或数组,决定哪些http请求可以匹配所装饰的方法,可以是单个字符串、或多个字符串的数组。

type:请求的类型,可以是http或json。描述了在何处查找请求参数以及如何序列化响应

auth:user,public,none

         user - 必须是已通过登录认证的用户,才能访问该请求。如果未经过登录直接访问,则会拦截并跳转回odoo登录页面。

        public - 使用公用的认证,可以不经过登录验证直接访问。

        none - 相应的方法总是可用,一般用于框架和认证模块,对应请求没有办法访问数据库或指向数据库的设置。

methos: 请求应用的http方法【PATCH, POST, PUT, DELETE】,默认全部方法。

cors: 跨域资源cors参数。

csrf:是否应为路由启用 CSRF 保护。默认情况下,对 '''http'''-类型的请求启用,对 '''json'''-类型的请求默认禁用

        1)如果表单是用python代码生成的,可通过request.csrf_token() 获取csrf

        2)如果表单是用javascript生成的,CSRF token会自动被添加到QWEB环境变量中,通过require('web.core').csrf_token获取

        3)如果终端可从其他地方以api或webhook形式调用,需要将对应的csrf禁用,此时最好用其他方式进行验证

当type="http"时,我们可以直接在网址上输入我们定义的路由,返回数据

当type="json"时,前端需要传入json数据,这里使用apifox演示

@http.route('/my_hostel/students/json', type='json', auth='none')
    def students_json(self):
        records = request.env['hostel.student'].sudo().search([])
        return records.read(['name'])

 

 

传入参数

 @http.route('/my_hostel/student_details', type='http', auth='none')
    def student_details(self, student_id):
        record = request.env['hostel.student'].sudo().browse(int(student_id))
        return u'<html><body><h1>%s</h1>Room No: %s' % (
            record.name,
            str(record.room_id.room_no) or 'none',
        )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DTCloud4

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值