In Odoo, controllers manage HTTP requests anddeliver appropriate responses. They are essential for defining thefunctionality and processing logic associated with different routes or endpointsin an Odoo module.
In Odoo, controllers handle various HTTPmethods such as GET, POST, PUT, and DELETE. They process client requests,execute necessary operations, and generate appropriate responses. This enablesdevelopers to build custom web pages, APIs, and web services within Odoo modules.
Request
In Odoo 18, the request API in the web controller allows for handling HTTP requests in a more interactive way within controllers, enabling you to manage incoming requests, extract data, send appropriate responses, and customizing requests. It also efficiently manages the errors and exceptions. This API is part of the odoo.http module, which is commonly used to create custom web controllers that manage specific routes or endpoints.
In Odoo, the request object is automatically assigned to odoo.http.request at the start of a request. Requests can generally be categorized into two types: HTTP and JSON requests.
HTTP requests, which use GET and POST methods, facilitate communication between the client and server. The client can send data either through the encoding data in the URL using GET or in the HTTP body using POST, offering flexibility in how data is transmitted.
JSON requests, on the other hand, streamline client-server interactions by enabling the client to call server methods with specific arguments, receive responses from these calls, and retrieve relevant data efficiently.
1. Class WebRequest(httprequest)
Odoo does not have a predefined WebRequest class; instead, it includes the HttpRequest class, which is extensively used to handle web requests. This class, located in the odoo.http module, is essential for managing HTTP requests in Odoo. It provides developers with numerous attributes and methods that are key for interacting with incoming HTTP requests, making it a central tool for web request management within the framework.
Parameters: httprequest: an encapsulated Werkzeug Request object
In Odoo, the httprequest parameter is accessible within a controller method that handles HTTP requests. This parameter represents the incoming HTTP request initiated by a client.
* user: It is an optional user or user id for changing the current user
* context: It is an optional context dictionary for changing the current context
* su: It is an optional boolean for changing the superuser mode
a. Properties:cr
The "cr" object in Odoo represents the database cursor object. The cr object functions as a database interface, facilitating interactions with database tables and enabling operations such as querying, creating, updating, and deleting records. It is commonly used within Odoo models and methods to execute database queries, manage transactions, and handle data operations efficiently.
b. Context
The context, which may be a dictionary or an object, consists of key-value pairs representing various contextual details. These include session attributes, localization settings, authorization credentials, request-specific parameters, and other relevant data essential for handling the request. Utilizing the context enables efficient mapping of these values to the active request, ensuring smooth processing.
c. Env
The environment (env) in Odoo represents a database session, providing access to models, records, and various functionalities of the Odoo framework. It plays a crucial role in enabling interactions with the database, allowing operations such as creating, retrieving, updating, and deleting records.
d. Session
For each HTTP request, it is typically handled within a session context. This context manages database transactions, user authentication, and other session-related details to ensure proper request processing.
e. DB
The 'db' parameter in an HTTP request identifies the specific database the request should interact with. This is particularly useful when managing multiple Odoo database instances. When sending an HTTP request to an Odoo server, the 'db' parameter can be specified either in the request URL or within the request payload.
* csrf_token(time_limit=None)
This method is used to generate a CSRF token. The CSRF token acts as a security mechanism to protect against Cross-Site Request Forgery (CSRF) attacks, ensuring that only trusted and authenticated sources can send requests to the server.
* Class HttpRequest(*args)
It is the controller's handler method that can accept keyword arguments corresponding to different parameter types. These include route parameters, query string parameters, form inputs, and file uploads, allowing for flexible processing of incoming HTTP requests.
* Routing Parameters
The routing parameters specified in the URL path are extracted and provided as keyword arguments to the controller's handler method. These parameters are explicitly defined within the route decorator.
* Query String Parameters
The Query string parameters consist of key-value pairs appended to the URL, and Odoo automatically processes these parameters. In Odoo 18, you can retrieve them via the params attribute of the http.request object in the controller.
* Form Parameters
Form parameters refer to the data sent through an HTML form. These parameters can be accessed via the form attribute of the http.request object in the controller.
* make_response(data, headers=None, cookies=None)
The make_response() function is used to create an HTTP response object that includes the given data, headers, and cookies. It is primarily utilized in controller methods to generate and return the appropriate response. The function accepts several parameters, allowing for customization of the response's content and behavior.
1. Data
The "data" refers to the content that is included in the response body. This can encompass various forms of data, such as JSON, XML, or HTML, depending on the request and the intended response. The data typically includes the result or any information that the server needs to send back to the client, ensuring the response is complete and formatted appropriately for the consuming application.
2. Headers:
Additional HTTP headers can be added to the response based on the headers received in the HTTP request .
3. Cookies
If cookies need to be set in the response, you can do so by adding them to the response object. The cookies are optional, allowing you to manage them based on your application requirements.
4. Template
When a template is included in an HTTP response, Odoo processes the template and sets it as the response content. The QWeb templating engine is used to generate dynamic web content in this process.
5. Qcontext
The qcontext is a dictionary that stores context variables for template rendering. It enables you to modify or add data to the context before the template is processed and rendered.
6. Lazy
When the lazy parameter is set to True, it postpones the rendering of the template until it's absolutely necessary, which is represented in a Boolean format. This approach ensures that the template is only rendered when the data is ready, optimizing performance.
7. Kw
The kw (short for keyword arguments) refers to a dictionary that holds key-value pairs. These pairs are used to pass extra arguments to the controller method, enabling fine-tuned control over the controller’s functionality and the subsequent 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 an 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
In Odoo 18, the Response API within the web controller framework is crucial for managing and customizing HTTP responses returned to the client. The Response API, typically used in combination with controller methods decorated by @http.route, provides flexibility for defining the type, format, and content of responses in web applications.
class Response(*args, **kw)
The Response class allows you to customize different aspects of an HTTP response, such as headers, content, and status code. It gives you more control over responses within your controller, enabling you to specify the content, set the status code, manage headers, add cookies, and adjust other response attributes as required.
Parameters: Return a dictionary containing the necessary key-value pairs to define settings for a response.
* Template: Specifies the template to render for HTML-based responses. If a template is provided, it will generate HTML output based on this template.
* qcontext: A dictionary that contains context variables for rendering the template. Useful for passing dynamic data from the controller to the template.
* uid: Represents the current user ID. Default is None if no user is logged in, which can help differentiate access or customize content based on user-specific permissions.
from odoo import http
class MyController(http.Controller):
@http.route('/my_route', type='http', auth='public')
def my_method(self, **kwargs):
data = "Hello, World!"
headers = [('Content-Type', 'text/plain')]
# Return a custom response with specific headers and status code
return http.Response(
data,
status=200,
headers=headers,
cookies={'session_id': 'xyz123'}
)
In conclusion, understanding the key elements of request and response handling in Odoo 18 controllers is essential for building efficient and responsive applications. By effectively managing requests and customizing responses, developers can enhance the functionality, security, and user experience of their applications. Leveraging the flexibility of the Request and Response classes allows for better control over data flow, helping to create a seamless interaction between users and the application. Embracing these techniques will empower developers to build robust, scalable solutions tailored to their business needs.
To read more about Key Elements of Controller Request & Response in Odoo 18, refer to our blog Key Elements of Controller Request & Response in Odoo 18.