Odoo Controllers

Understanding Odoo Controllers: An Introduction

Understanding Odoo Controllers: An Introduction

In Odoo, controllers are essential components that manage HTTP requests and responses, enabling interaction between the user and the server. They play a crucial role in web development by defining routes that correspond to specific URL patterns and executing actions when those URLs are accessed. Controllers are used for a variety of purposes, such as handling form submissions, creating RESTful APIs, rendering web pages, and more. For example, a controller might be used to process data from a user-submitted form, fetch information from the database to display on a webpage, or track user interactions like email opens.

To illustrate, let's consider a few scenarios where controllers are indispensable:

1. Handling Form Submissions: When a user fills out a form on a website and clicks submit, a controller can process this data, validate it, and save it to the database.

Example: Handling Form Submissions in Odoo

In Odoo, the http.Controller class is used to create a controller. Within this class, you define methods that handle different routes. The @http.route decorator is used to specify the URL pattern, the type of HTTP request (GET, POST, etc.), and the authentication method. Here’s an example:

from odoo import http
from odoo.http import request

class MyFormController(http.Controller):
    @http.route('/submit_form', type='http', 
​ auth='public', methods=['POST'], csrf=False) def submit_form(self, **post): name = post.get('name') email = post.get('email') # Process the form data request.env['res.partner'].sudo().create({ 'name': name, 'email': email, }) return request.render('my_module.thank_you_page')

Breaking Down the Code:

  • Controller Class: MyFormController inherits from http.Controller, making it a controller class.
  • Route Decorator: @http.route('/submit_form', type='http', auth='public', methods=['POST'], csrf=False):
    • /submit_form: The URL pattern that triggers this method.
    • type='http': Specifies that this route handles HTTP requests.
    • auth='public': Indicates that this route can be accessed without authentication.
    • methods=['POST']: Specifies that this route only handles POST requests. POST requests are used to submit data to the server.
    • csrf=False: Disables Cross-Site Request Forgery (CSRF) protection for this route. In production, it's recommended to enable CSRF protection.
  • Method Definition: def submit_form(self, **post):
    • self: Refers to the instance of the controller.
    • **post: Captures all POST data submitted through the form as a dictionary.
  • Accessing Form Data:
    • name = post.get('name'): Retrieves the value of the 'name' field from the form data.
    • email = post.get('email'): Retrieves the value of the 'email' field from the form data.
  • Processing Data:
    • request.env['res.partner'].sudo().create({'name': name, 'email': email}): Creates a new partner record in the database using the submitted form data. The sudo() method is used to bypass record rules and access rights.
  • Response:
    • return request.render('my_module.thank_you_page'): Renders a thank you page to the user after the form is submitted successfully.

2. Creating APIs:

Controllers can be used to create APIs that allow external applications to interact with Odoo's data and functionality. This is particularly useful for integrating Odoo with other systems.

class MyAPIController(http.Controller):
    @http.route('/api/get_partners', type='json', auth='user')
    def get_partners(self):
        partners = request.env['res.partner'].search([])
        return [{'id': partner.id, 'name': partner.name} for partner in partners]
  • Route Decorator:
    • /api/get_partners: The URL pattern for the API endpoint.
    • type='json': Specifies that the response is in JSON format.
    • auth='user': Requires user authentication to access this route.
  • Method Definition
    • def get_partners(self) handles the request.
  • Fetching Data
    • request.env['res.partner'].search([]) retrieves all partners from the database.
  • Response
    • Returns a list of dictionaries containing partner IDs and names in JSON format.


3. Tracking User Interactions:

For example, to track whether a user has opened an email, a controller can serve a small tracking pixel that records the event when the email is viewed.


class EmailTrackingController(http.Controller):
    @http.route('/mail/tracking_pixel/<int:mail_id>', type='http', auth='public', methods=['GET'], csrf=False)
    def tracking_pixel(self, mail_id, **kwargs):
        mail = request.env['mail.mail'].browse(mail_id)
        if mail.exists():
            mail.sudo().write({'opened': True})  # Mark email as opened
        response = request.make_response(
            None,
            headers=[('Content-Type', 'image/gif')]
        )
        return response


  • Route Decorator:
    • /mail/tracking_pixel/<int:mail_id>: The URL pattern that includes a dynamic segment for the mail ID.
    • type='http': Specifies that this route handles HTTP requests.
    • auth='public': Allows access without authentication.
    • methods=['GET']: Specifies that this route only handles GET requests, typically used for fetching data.
    • csrf=False: Disables CSRF protection for this route.
  • Method Definition: def tracking_pixel(self, mail_id, **kwargs):
    • mail_id: Captures the mail ID from the URL.
  • Processing Data:
    • request.env['mail.mail'].browse(mail_id) fetches the mail record.
    • mail.sudo().write({'opened': True}) marks the email as opened.
  • Response:
    • Returns a 1x1 pixel GIF image as the response.

Summary

These examples demonstrate how Odoo controllers facilitate various functionalities, such as handling form submissions, creating APIs, and tracking user interactions. The @http.route decorator is key in mapping URLs to controller methods and specifying the HTTP request type. By managing the flow of data between the client and the server, controllers ensure that user interactions are seamlessly processed and responded to, enhancing the overall user experience.


We hope you found this information useful. ​

If you need help with customizing the Website modules or Controllers, please write to us in our LiveChat.
For technical questions, ask it in our LiveChat and specify your email so we can prepare an answer and send it for you.



Effective Use of Monkey Patching in Odoo Development