[IMP] core: docstring improvements

* clean and improve docstrings in orm
* fix typos found with codespell
* rely on the Environment class docstring instead of doc content (and
therefore move part of the doc inside the class docstring)

closes odoo/odoo#102969

X-original-commit: 8250cd4b210005d223a4cdb8afa4014425ca6fa3
Related: odoo/documentation#2803
Signed-off-by: Victor Feyens (vfe) <vfe@odoo.com>
This commit is contained in:
Victor Feyens
2022-10-10 19:55:37 +02:00
parent e4f81af515
commit 9ded78ede0
4 changed files with 61 additions and 48 deletions
+26 -19
View File
@@ -464,16 +464,16 @@ def call_kw(model, name, args, kwargs):
class Environment(Mapping):
""" An environment wraps data for ORM records:
""" The environment stores various contextual data used by the ORM:
- :attr:`cr`, the current database cursor;
- :attr:`uid`, the current user id;
- :attr:`context`, the current context dictionary;
- :attr:`su`, whether in superuser mode.
- :attr:`cr`: the current database cursor (for database queries);
- :attr:`uid`: the current user id (for access rights checks);
- :attr:`context`: the current context dictionary (arbitrary metadata);
- :attr:`su`: whether in superuser mode.
It provides access to the registry by implementing a mapping from model
names to new api models. It also holds a cache for records, and a data
structure to manage recomputations.
It provides access to the registry by implementing a mapping from model
names to models. It also holds a cache for records, and a data
structure to manage recomputations.
"""
@classproperty
def envs(cls):
@@ -556,13 +556,14 @@ class Environment(Mapping):
def __call__(self, cr=None, user=None, context=None, su=None):
""" Return an environment based on ``self`` with modified parameters.
:param cr: optional database cursor to change the current cursor
:param user: optional user/user id to change the current user
:param context: optional context dictionary to change the current context
:param su: optional boolean to change the superuser mode
:type context: dict
:type user: int or :class:`~odoo.addons.base.models.res_users`
:type su: bool
:param cr: optional database cursor to change the current cursor
:type cursor: :class:`~odoo.sql_db.Cursor`
:param user: optional user/user id to change the current user
:type user: int or :class:`res.users record<~odoo.addons.base.models.res_users.Users>`
:param dict context: optional context dictionary to change the current context
:param bool su: optional boolean to change the superuser mode
:returns: environment with specified args (new or existing one)
:rtype: :class:`Environment`
"""
cr = self.cr if cr is None else cr
uid = self.uid if user is None else int(user)
@@ -571,7 +572,13 @@ class Environment(Mapping):
return Environment(cr, uid, context, su)
def ref(self, xml_id, raise_if_not_found=True):
"""Return the record corresponding to the given ``xml_id``."""
""" Return the record corresponding to the given ``xml_id``.
:param str xml_id: record xml_id, under the format ``<module.id>``
:param bool raise_if_not_found: whether the method should raise if record is not found
:returns: Found record or None
:raise ValueError: if record wasn't found and ``raise_if_not_found`` is True
"""
res_model, res_id = self['ir.model.data']._xmlid_to_res_model_res_id(
xml_id, raise_if_not_found=raise_if_not_found
)
@@ -603,7 +610,7 @@ class Environment(Mapping):
"""Return the current user (as an instance).
:returns: current user - sudoed
:rtype: :class:`~odoo.addons.base.models.res_users`"""
:rtype: :class:`res.users record<~odoo.addons.base.models.res_users.Users>`"""
return self(su=True)['res.users'].browse(self.uid)
@lazy_property
@@ -615,7 +622,7 @@ class Environment(Mapping):
:raise AccessError: invalid or unauthorized `allowed_company_ids` context key content.
:return: current company (default=`self.user.company_id`), with the current environment
:rtype: res.company
:rtype: :class:`res.company record<~odoo.addons.base.models.res_company.Company>`
.. warning::
@@ -645,7 +652,7 @@ class Environment(Mapping):
:raise AccessError: invalid or unauthorized `allowed_company_ids` context key content.
:return: current companies (default=`self.user.company_ids`), with the current environment
:rtype: res.company
:rtype: :class:`res.company recordset<~odoo.addons.base.models.res_company.Company>`
.. warning::
+26 -20
View File
@@ -102,7 +102,7 @@ ir.http._post_dispatch/Dispatcher.post_dispatch
route_wrapper, closure of the http.route decorator
Sanitize the request parameters, call the route endpoint and
optionaly coerce the endpoint result.
optionally coerce the endpoint result.
endpoint
The @route(...) decorated controller method.
@@ -207,7 +207,7 @@ CSRF_TOKEN_SALT = 60 * 60 * 24 * 365
# The default lang to use when the browser doesn't specify it
DEFAULT_LANG = 'en_US'
# The dictionnary to initialise a new session with.
# The dictionary to initialise a new session with.
def get_default_session():
return {
'context': {}, # 'lang': request.default_lang() # must be set at runtime
@@ -509,7 +509,7 @@ class Stream:
should offer to save the file instead of displaying it.
:param bool immutable: Add the ``immutable`` directive to the
``Cache-Control`` response header, allowing intermediary
proxies to aggresively cache the response. This option
proxies to aggressively cache the response. This option
also set the ``max-age`` directive to 1 year.
:param send_file_kwargs: Other keyword arguments to send to
:func:`odoo.tools._vendor.send_file.send_file` instead of
@@ -983,7 +983,7 @@ class Response(werkzeug.wrappers.Response):
this class's constructor can take the following additional
parameters for QWeb Lazy Rendering.
:param basestring template: template to render
:param str template: template to render
:param dict qcontext: Rendering context to use
:param int uid: User id to use for the ir.ui.view render call,
``None`` to use the request's user (the default)
@@ -1088,7 +1088,7 @@ class FutureResponse:
class Request:
"""
Wrapper around the incomming HTTP request with deserialized request
Wrapper around the incoming HTTP request with deserialized request
parameters, session utilities and request dispatching logic.
"""
@@ -1150,7 +1150,13 @@ class Request:
# Getters and setters
# =====================================================
def update_env(self, user=None, context=None, su=None):
""" Update the environment of the current request. """
""" Update the environment of the current request.
:param user: optional user/user id to change the current user
:type user: int or :class:`res.users record<~odoo.addons.base.models.res_users.Users>`
:param dict context: optional context dictionary to change the current context
:param bool su: optional boolean to change the superuser mode
"""
cr = None # None is a sentinel, it keeps the same cursor
self.env = self.env(cr, user, context, su)
threading.current_thread().uid = self.env.uid
@@ -1159,7 +1165,7 @@ class Request:
"""
Override the environment context of the current request with the
values of ``overrides``. To replace the entire context, please
use :meth:`~update_env`: instead.
use :meth:`~update_env` instead.
"""
self.update_env(context=dict(self.env.context, **overrides))
@@ -1197,7 +1203,7 @@ class Request:
Get the remote address geolocalisation.
When geolocalization is successful, the return value is a
dictionary whoose format is:
dictionary whose format is:
{'city': str, 'country_code': str, 'country_name': str,
'latitude': float, 'longitude': float, 'region': str,
@@ -1421,11 +1427,11 @@ class Request:
the dispatching. Meanwhile, the template and/or qcontext can be
altered or even replaced by a static response.
:param basestring template: template to render
:param str template: template to render
:param dict qcontext: Rendering context to use
:param bool lazy: whether the template rendering should be deferred
until the last possible moment
:param kw: forwarded to werkzeug's Response object
:param dict kw: forwarded to werkzeug's Response object
"""
response = Response(template=template, qcontext=qcontext, **kw)
if not lazy:
@@ -1514,7 +1520,7 @@ class Request:
# the registry. That means either
# - the database probably does not exists anymore, or
# - the database is corrupted, or
# - the database version doesnt match the server version.
# - the database version doesn't match the server version.
# So remove the database from the cookie
self.db = None
self.session.db = None
@@ -1613,7 +1619,7 @@ class Dispatcher(ABC):
def dispatch(self, endpoint, args):
"""
Extract the params from the request's body and call the
endpoint. While it is prefered to override ir.http._pre_dispatch
endpoint. While it is preferred to override ir.http._pre_dispatch
and ir.http._post_dispatch, this method can be override to have
a tight control over the dispatching.
"""
@@ -1648,7 +1654,7 @@ class HttpDispatcher(Dispatcher):
body and query-string and checking cors/csrf while dispatching a
request to a ``type='http'`` route.
See :meth:`~odoo.http.Response.load`: method for the compatible
See :meth:`~odoo.http.Response.load` method for the compatible
endpoint return types.
"""
self.request.params = dict(self.request.get_http_params(), **args)
@@ -1679,9 +1685,9 @@ class HttpDispatcher(Dispatcher):
could be delivered and that the request ``Content-Type`` was not
json.
:param exc Exception: the exception that occured.
:param Exception exc: the exception that occurred.
:returns: an HTTP error response
:rtype: werkzeug.wrapper.Response
:rtype: :class:`werkzeug.wrapper.Response`
"""
if isinstance(exc, SessionExpiredException):
session = self.request.session
@@ -1727,7 +1733,7 @@ class JsonRPCDispatcher(Dispatcher):
the session context via a special ``context`` argument that is
removed prior to calling the endpoint.
Sucessful request::
Successful request::
--> {"jsonrpc": "2.0", "method": "call", "params": {"context": {}, "arg1": "val1" }, "id": null}
@@ -1758,12 +1764,12 @@ class JsonRPCDispatcher(Dispatcher):
def handle_error(self, exc):
"""
Handle any exception that occured while dispatching a request to
a `type='json'` route. Also handle exceptions that occured when
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 request ``Content-Type`` was json.
:param exc Exception: the exception that occured.
:param exc Exception: the exception that occurred.
:returns: an HTTP error response
:rtype: Response
"""
@@ -1921,7 +1927,7 @@ class Application:
return
ProxyFix(fake_app)(environ, fake_start_response)
# Some URLs in website are concatened, first url ends with /,
# Some URLs in website are concatenated, first url ends with /,
# second url starts with /, resulting url contains two following
# slashes that must be merged.
if environ['REQUEST_METHOD'] == 'GET' and '//' in environ['PATH_INFO']:
+8 -8
View File
@@ -622,7 +622,6 @@ class BaseModel(metaclass=MetaModel):
This "registry" class carries inferred model metadata, and inherits (in
the Python sense) from all classes that define the model, and possibly
other registry classes.
"""
if getattr(cls, '_constraints', None):
_logger.warning("Model attribute '_constraints' is no longer supported, "
@@ -934,10 +933,10 @@ class BaseModel(metaclass=MetaModel):
def _export_rows(self, fields, *, _is_toplevel_call=True):
""" Export fields of the records in ``self``.
:param fields: list of lists of fields to traverse
:param bool _is_toplevel_call:
used when recursing, avoid using when calling from outside
:return: list of lists of corresponding values
:param list fields: list of lists of fields to traverse
:param bool _is_toplevel_call:
used when recursing, avoid using when calling from outside
:return: list of lists of corresponding values
"""
import_compatible = self.env.context.get('import_compat', True)
lines = []
@@ -1049,10 +1048,11 @@ class BaseModel(metaclass=MetaModel):
def export_data(self, fields_to_export):
""" Export fields for selected objects
:param fields_to_export: list of fields
:rtype: dictionary with a *datas* matrix
This method is used when exporting data via client menu
This method is used when exporting data via client menu
:param list fields_to_export: list of fields
:returns: dictionary with a *datas* matrix
:rtype: dict
"""
if not (self.env.is_admin() or self.env.user.has_group('base.group_allow_export')):
raise UserError(_("You don't have the rights to export data. Please contact an Administrator."))
+1 -1
View File
@@ -257,7 +257,7 @@ def showwarning_with_traceback(message, category, filename, lineno, file=None, l
if category is BytesWarning and message.args[0] in IGNORE:
return
# find the stack frame maching (filename, lineno)
# find the stack frame matching (filename, lineno)
filtered = []
for frame in traceback.extract_stack():
if 'importlib' not in frame.filename: