Enable Dark Mode!
key-elements-of-controller-request-and-response-in-odoo-17.jpg
By: Unnimaya CO

Key Elements of Controller Request & Response in Odoo 17

Technical

In Odoo, controllers serve the purpose of managing HTTP requests and delivering suitable responses. They play a pivotal role in defining the functionality and processing logic for various routes or endpoints within an Odoo module.

In Odoo, controllers are tasked with managing different HTTP methods like GET, POST, PUT, DELETE, and more. They receive requests from clients, execute required operations, and produce relevant responses. This capability enables developers to craft custom web pages, APIs, and web services within an Odoo module.

Request

Requests offer a user-friendly and intuitive API for interfacing with web services, APIs, and websites. It facilitates tasks such as sending HTTP requests, managing response data, customizing requests, and handling errors and exceptions efficiently.

At the start of a request in Odoo, the request object is automatically assigned to the variable `odoo.http.request`.

There are primarily two types of requests: HTTP Request and JSON Request.

Utilizing HTTP requests via the GET and POST methods facilitates communication between the client and server. The client has the option to send a request to the server by encoding it in the URL using the GET method or by placing it in the HTTP body using the POST method, providing flexibility and versatility in data transmission.

JsonRequest streamlines client-server communication by invoking methods on the server with supplied arguments. Subsequently, the client can receive responses from these method calls, enabling the retrieval of pertinent data.

1. Class WebRequest(httprequest)

The class WebRequest is not a predefined class in Odoo. However, Odoo does offer a class called HttpRequest, which is frequently utilized for managing web requests.

The odoo.http module hosts the HttpRequest class, serving as the cornerstone for managing HTTP requests within Odoo. This class equips developers with a multitude of attributes and methods crucial for engaging with incoming HTTP requests.

Parameters: httprequest - an encapsulated Werkzeug Request object

In Odoo, the httprequest parameter is accessible when defining a controller method tasked with handling HTTP requests. It signifies the inbound HTTP request initiated by a client.

Properties:
cr

The "cr" object in Odoo represents the database cursor object. It serves as a database interface provided by Odoo, enabling interaction with the database tables and execution of database operations such as querying, creating, updating, and deleting records.

This "cr" object is commonly employed within Odoo models and methods to execute database queries, conduct transactions, and oversee data management tasks.

Context

The context, which can be either a dictionary or an object, encompasses key-value pairs embodying diverse contextual information. This encompasses details like the user's session attributes, localization preferences, authorization data, request-specific parameters, or any other pertinent information pivotal for processing the request. Leveraging the context facilitates mapping these values to the current request, aiding in seamless processing.

Env

The environment in Odoo symbolizes a database session, furnishing access to models, records, and other functionalities within the Odoo framework. Serving as a vital component, it empowers users to interact with the database, facilitating diverse operations like record creation, retrieval, updating, and deletion.

Session

During each HTTP request, it's customary to be managed within a session context. This context oversees database transactions, user authentication, and other session-specific details.

DB

The 'db' parameter within an HTTP request serves to designate the target database for that request. This parameter enables you to specify the precise database with which the request should interact, particularly useful in scenarios involving multiple Odoo database instances.

When initiating an HTTP request to an Odoo server, the 'db' parameter can be incorporated either directly in the request URL or as a parameter within the request payload.

* csrf_token(time_limit=None)

This method is employed to generate a Cross-Site Request Forgery (CSRF) token. The CSRF token serves as a security measure aimed at safeguarding against CSRF attacks, guaranteeing that requests sent to the server originate solely from trusted and authenticated sources.

* Class HttpRequest(*args) 

The handler methods for HTTP requests in controller classes are capable of accepting keyword arguments that correlate with various types of parameters. These parameters may include routing parameters, query string parameters, form parameters, and files, enabling versatile handling of incoming requests.

* Routing Parameters

Parameters defined in the URL path are extracted and passed as keyword arguments to the handler method. These parameters are explicitly defined within the route decorator.

* Query String Parameters

Query string parameters are composed of key-value pairs that are added to the end of the URL. Odoo automatically parses these parameters, and they can be accessed through the params attribute of the http.request object.

* Form Parameters

Form parameters refer to the data submitted via an HTML form. These parameters are accessible using the form attribute of the http.request object.

* make_response(data, headers=None, cookies=None)

The make_response() function in Odoo is utilized to generate an HTTP response object containing the provided data, headers, and cookies. It's commonly employed within controller methods to craft and deliver the desired response. Parameters within make_response() include:

1. Data: The data to be included in the response body.

2. Headers: Optional. Additional HTTP headers to be included in the response.

3. Cookies: Optional. Cookies to be set in the response.

4. Template: When incorporating a template in an HTTP response, Odoo renders the template and assigns it as the response content. Odoo relies on the QWeb templating engine to generate dynamic web content.

5. qcontext: Dictionary that holds context variables used during template rendering. It allows you to modify or include data before the template is rendered.

6. Lazy: When set to True, defers template rendering until the last moment, indicated in Boolean format.

7. Kw: Dictionary containing key-value pairs. These pairs represent additional arguments passed to the controller method, allowing customization of both the controller's behavior and the resulting HTTP response.

2. Class JsonRequest(*args)

Successful request:

Odoo can handle JSON requests within a controller by accessing and parsing the request payload as JSON data.

Request:

{"jsonrpc": "2.0",
"method": "call",
"params": {"context": {},
           "arg1": "val1"},
"id": null}

Response:

{"jsonrpc": "2.0",
"result": {"res1": "val1"},
"id": null}

Request producing a error:

Request:

{"jsonrpc": "2.0",
   "method": "call",
   "params": {"context": {},
              "arg1": "val1" },
   "id": null}

Response:

{"jsonrpc": "2.0",
    "error": {"code": 1,
              "message": "End user error message.",
              "data": {"code": "codestring",
                       "debug": "traceback" } },
    "id": null}

Response

class Response(*args, **kw)

The Response class enables you to customize various attributes of an HTTP response, including headers, content, status code, and more. It provides greater control over the HTTP response within your controller, allowing you to set the content, status code, headers, cookies, and other attributes as needed.

Parameters:

Return a dictionary with the desired key-value pairs to set parameters in a response.

Template : The template used to render the response output.

qcontext : A dictionary used for rendering. 

Uid : The current user ID, with a default value of None.

This facilitates obtaining key elements and aspects of controller requests and responses in Odoo 17.

To read more about Key Elements of Controller Request & Response in Odoo 16, refer to our blog Key Elements of Controller Request & Response in Odoo 16.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message