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',
)