Web Controllers¶
Controllers¶
Controllers need to provide extensibility, much like
Model
, but can’t use the same mechanism as the
pre-requisites (a database with loaded modules) may not be available yet (e.g.
no database created, or no database selected).
Controllers thus provide their own extension mechanism, separate from that of models:
Controllers are created by inheriting from Controller
.
Routes are defined through methods decorated with route()
:
class MyController(odoo.http.Controller):
@route('/some_url', auth='public')
def handler(self):
return stuff()
To override a controller, inherit from its class and override relevant methods, re-exposing them if necessary:
class Extension(MyController):
@route()
def handler(self):
do_before()
return super(Extension, self).handler()
decorating with
route()
is necessary to keep the method (and route) visible: if the method is redefined without decorating, it will be 「unpublished」the decorators of all methods are combined, if the overriding method’s decorator has no argument all previous ones will be kept, any provided argument will override previously defined ones e.g.:
class Restrict(MyController): @route(auth='user') def handler(self): return super(Restrict, self).handler()
will change
/some_url
from public authentication to user (requiring a log-in)
API¶
Routing¶
- @odoo.http.route(route=None, **routing)[原始碼]¶
Decorate a controller method in order to route incoming requests matching the given URL and options to the decorated method.
警告
It is mandatory to re-decorate any method that is overridden in controller extensions but the arguments can be omitted. See
Controller
for more details.- 參數
route (Union[str, Iterable[str]]) – The paths that the decorated method is serving. Incoming HTTP request paths matching this route will be routed to this decorated method. See werkzeug routing documentation for the format of route expressions.
type (str) – The type of request, either
'json'
or'http'
. It describes where to find the request parameters and how to serialize the response.auth (str) –
The authentication method, one of the following:
'user'
: The user must be authenticated and the current request will be executed using the rights of the user.'public'
: The user may or may not be authenticated. If he isn’t, the current request will be executed using the shared Public user.'none'
: The method is always active, even if there is no database. Mainly used by the framework and authentication modules. The request code will not have any facilities to access the current user.
methods (Iterable[str]) – A list of http methods (verbs) this route applies to. If not specified, all methods are allowed.
cors (str) – The Access-Control-Allow-Origin cors directive value.
csrf (bool) – Whether CSRF protection should be enabled for the route. Enabled by default for
'http'
-type requests, disabled by default for'json'
-type requests.
Request¶
The request object is automatically set on odoo.http.request
at
the start of the request.
- class odoo.http.Request(httprequest)[原始碼]¶
Wrapper around the incoming HTTP request with deserialized request parameters, session utilities and request dispatching logic.
- update_context(**overrides)[原始碼]¶
Override the environment context of the current request with the values of
overrides
. To replace the entire context, please useupdate_env()
instead.
- property geoip¶
Get the remote address geolocalisation.
When geolocalization is successful, the return value is a dictionary whose format is:
- {『city』: str, 『country_code』: str, 『country_name』: str,
『latitude』: float, 『longitude』: float, 『region』: str, 『time_zone』: str}
When geolocalization fails, an empty dict is returned.
- default_lang()[原始碼]¶
Returns default user language according to request specification
- 回傳
Preferred language if specified or 『en_US』
- 回傳型別
- get_http_params()[原始碼]¶
Extract key=value pairs from the query string and the forms present in the body (both application/x-www-form-urlencoded and multipart/form-data).
- 回傳
The merged key-value pairs.
- 回傳型別
- make_response(data, headers=None, cookies=None, status=200)[原始碼]¶
Helper for non-HTML responses, or HTML responses with custom response headers or cookies.
While handlers can just return the HTML markup of a page they want to send as a string if non-HTML data is returned they need to create a complete response object, or the returned data will not be correctly interpreted by the clients.
- 參數
data (str) – response body
status (int) – http status code
headers (
[(name, value)]
) – HTTP headers to set on the responsecookies (collections.abc.Mapping) – cookies to set on the client
- 回傳
a response object.
- 回傳型別
- make_json_response(data, headers=None, cookies=None, status=200)[原始碼]¶
Helper for JSON responses, it json-serializes
data
and sets the Content-Type header accordingly if none is provided.- 參數
data – the data that will be json-serialized into the response body
status (int) – http status code
headers (List[(str, str)]) – HTTP headers to set on the response
cookies (collections.abc.Mapping) – cookies to set on the client
- 回傳型別
- class odoo.http.JsonRPCDispatcher(request)[原始碼]¶
- classmethod is_compatible_with(request)[原始碼]¶
Determine if the current request is compatible with this dispatcher.
- dispatch(endpoint, args)[原始碼]¶
JSON-RPC 2 over HTTP.
Our implementation differs from the specification on two points:
The
method
member of the JSON-RPC request payload is ignored as the HTTP path is already used to route the request to the controller.We only support parameter structures by-name, i.e. the
params
member of the JSON-RPC request payload MUST be a JSON Object and not a JSON Array.
In addition, it is possible to pass a context that replaces the session context via a special
context
argument that is removed prior to calling the endpoint.Successful request:
--> {"jsonrpc": "2.0", "method": "call", "params": {"context": {}, "arg1": "val1" }, "id": null} <-- {"jsonrpc": "2.0", "result": { "res1": "val1" }, "id": null}
Request producing a error:
--> {"jsonrpc": "2.0", "method": "call", "params": {"context": {}, "arg1": "val1" }, "id": null} <-- {"jsonrpc": "2.0", "error": {"code": 1, "message": "End user error message.", "data": {"code": "codestring", "debug": "traceback" } }, "id": null}
- handle_error(exc: Exception) collections.abc.Callable [原始碼]¶
Handle any exception that occurred while dispatching a request to a
type='json'
route. Also handle exceptions that occurred when no route matched the request path, that no fallback page could be delivered and that the requestContent-Type
was json.- 參數
exc – the exception that occurred.
- 回傳
a WSGI application
- class odoo.http.HttpDispatcher(request)[原始碼]¶
- classmethod is_compatible_with(request)[原始碼]¶
Determine if the current request is compatible with this dispatcher.
- dispatch(endpoint, args)[原始碼]¶
Perform http-related actions such as deserializing the request body and query-string and checking cors/csrf while dispatching a request to a
type='http'
route.See
load()
method for the compatible endpoint return types.
- handle_error(exc: Exception) collections.abc.Callable [原始碼]¶
Handle any exception that occurred while dispatching a request to a
type='http'
route. Also handle exceptions that occurred when no route matched the request path, when no fallback page could be delivered and that the requestContent-Type
was not json.- 參數
exc (Exception) – the exception that occurred.
- 回傳
a WSGI application
Response¶
- class odoo.http.Response(*args, **kw)[原始碼]¶
Outgoing HTTP response with body, status, headers and qweb support. In addition to the
werkzeug.wrappers.Response
parameters, this class’s constructor can take the following additional parameters for QWeb Lazy Rendering.- 參數
these attributes are available as parameters on the Response object and can be altered at any time before rendering
Also exposes all the attributes and methods of
werkzeug.wrappers.Response
.- classmethod load(result, fname='<function>')[原始碼]¶
Convert the return value of an endpoint into a Response.
- 參數
result (Union[Response, werkzeug.wrappers.BaseResponse, werkzeug.exceptions.HTTPException, str, bytes, NoneType]) – The endpoint return value to load the Response from.
fname (str) – The endpoint function name wherefrom the result emanated, used for logging.
- 回傳
The created
Response
.- 回傳型別
- 引發
TypeError – When
result
type is none of the above- mentioned type.
- flatten()[原始碼]¶
Forces the rendering of the response’s template, sets the result as response body and unsets
template
- set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None, cookie_type='required')[原始碼]¶
Sets a cookie.
A warning is raised if the size of the cookie header exceeds
max_cookie_size
, but the header will still be set.- 參數
key – the key (name) of the cookie to be set.
value – the value of the cookie.
max_age – should be a number of seconds, or
None
(default) if the cookie should last only as long as the client’s browser session.expires – should be a
datetime
object or UNIX timestamp.path – limits the cookie to a given path, per default it will span the whole domain.
domain – if you want to set a cross-domain cookie. For example,
domain=".example.com"
will set a cookie that is readable by the domainwww.example.com
,foo.example.com
etc. Otherwise, a cookie will only be readable by the domain that set it.secure – If
True
, the cookie will only be available via HTTPS.httponly – Disallow JavaScript access to the cookie.
samesite – Limit the scope of the cookie to only be attached to requests that are 「same-site」.