my_module/__init__.py
在開始controller設定之前,我們必須先將我們controllers給import進去
from . import contorllers
my_module/controllers/__init__.py
在開始controller設定之前,我們必須先將我們library_controller.py給import進去
from . import library_contorller
@http.route
from odoo import http
from odoo.http import request
class library_contorller(http.Controller):
@http.route('/my_library/books',method=['GET'], type='http', auth='none')
def books(self):
books = request.env['library.book'].sudo().search([])
html_result = '<html><body><ul>'
for book in books:
html_result += "<li> %s </li>" % book.name
html_result += '</ul></body></html>'
return html_result
在@route('/my_library/books', type='http', auth='none')
當中'/my_library/books'
就是我們的網址後綴,還有我們使用了type='http'
,透過request.env[]
將library.book
中
所有recordset給抓出來並透過for來將他們列出來 ; auth='none'
代表任何人都可以訪問.../my_library/books
這個網址。
或者我們也可以指定template來顯示:
from odoo import http
class LibraryController(http.Controller):
@http.route('/my_library/books', auth='user')
def list_books(self, **kwargs):
book_model = http.request.env['library.book']
books = book_model.sudo().search([])
return http.request.render('library.library_template', {'books': books})
我們透過render來將objs的值,回傳給library_template當中對應的'objs',並且這次我們將指定只有user群組可以看到畫面auth='user'
。
我們也可以透過json來製作api
import json
from odoo import http, tools
class BookController(http.Controller):
@http.route('/book', methods=['POST'], type='json', auth='public', csrf=False)
def create_book(self, **kwargs):
data = http.request.jsonrequest
book_name = data.get('name')
author = data.get('author')
result = {'author': author}
response = json.dumps(result, default=tools.json_default)
return http.Response(response, status=200, headers=[('Content-Type', 'application/json')])
from odoo import http
@http.router('/book',metho=['POST'],type='json',auth='*',csrf=False)
def create_book(self, **kwargs):
data = http.request.jsonrequest
book_name = data.get('name')
author = data.get('author')
result = {'author': author}
response = json.dumps(result, default=data_utils.json_default)
return response
website=True
當我們在@http.router中加入website=True
之後,我們將會直接套用odoo的網頁主題:
'depends': [..., 'website'],
之後我們在先前的程式碼加入website=True
:
from odoo import http
class LibraryController(http.Controller):
@http.route('/my_library/books', auth='user', website=True)
def list_books(self, **kwargs):
book_model = http.request.env['library.book']
books = book_model.sudo().search([])
return http.request.render('library.library_template', {'books': books})