Odooly API¶
The library provides few objects to access the Odoo model and the associated services of the Odoo API.
The signature of the methods mimics the standard methods provided by the
odoo.models.Model Odoo class. This is intended to help the developer
when developping addons. What is experimented at the interactive prompt
should be portable in the application with little effort.
Client and Services¶
The Client object provides thin wrappers around Odoo Webclient API
and RPC services and their methods. Additional helpers are provided on the
Client.env environment, to explore the models and to list or to install
Odoo add-ons. Please refer to Env documentation below.
- class odooly.Client(server, db=None, user=None, password=None, api_key=None, verbose=False)[source]¶
Connection to an Odoo instance.
This is the top level object. The server is the URL of the instance, like
http://localhost:8069. If server is anodooPython package, it is used to connect to the local server.The db is the name of the database and the user should exist in the table
res.users. If the password is not provided, it will be asked on login.
- classmethod Client.from_config(environment, user=None, verbose=False)[source]¶
Create a connection to a defined environment.
See
Client.get_config()Return a connectedClient.
- Client.create_database(passwd, database, demo=False, lang='en_US', user_password='admin', login='admin', country_code=None)[source]¶
Create a new database.
The superadmin passwd and the database name are mandatory. By default, demo data are not loaded, lang is
en_USand no country is set into the database. Login if successful.
- Client.clone_database(passwd, database, neutralize_database=False)[source]¶
Clone the current database.
The superadmin passwd and database are mandatory. Login if successful.
- Client.drop_database(passwd, database)[source]¶
Drop the database.
The superadmin passwd and database are mandatory.
- Client.login(user, password=None, database=None, api_key=None)[source]¶
Switch user and (optionally) database.
- Client.save(environment=None, skip=False)[source]¶
Save environment settings with this name, or current name
- classmethod Client.get_config(environment)[source]¶
Retrieve the settings for this environment.
It can be in memory, if it was saved before with
Client.save(). If not, it will parseodooly.inifile, where it searches for the section[ <environment> ].See
read_config()for details of the configuration file format.
Note
In interactive mode, a method
Client.connect(env=None, server=None, database=None, user=None) exists,
to connect to another environment, and recreate the globals().
Note
If the HTTPS server certificate is invalid, there’s a trick to bypass the
certificate verification, when the environment variable is set
ODOOLY_SSL_UNVERIFIED=1.
Odoo Webclient API¶
These HTTP routes were developed for the Odoo Web application. They are used
by Odooly to provide high level methods on Env and Model.
The database endpoint exposes few methods which might be helpful
for database management. Use dir() function to introspect them.
- class odooly.WebAPI(client, endpoint, methods)[source]¶
A wrapper around Web endpoints.
The connected endpoints are exposed on the Client instance. Argument client is the connected Client. Argument endpoint is the name of the service (examples:
"web/database","web/session"). Argument methods is the list of methods which should be exposed on this endpoint. Usedir(...)on the instance to list them.
Odoo RPC Services¶
The Odoo RPC services are exposed too. They could be used for server and
database operations.
The common service provided methods which might be helpful for server
administration. Use the dir() function to introspect them. The _object
service should not be used directly. It provides same feature as the
web_dataset Webclient endpoint. Use Env and Model
instead.
Please refer to the Odoo documentation for more details.
Note
These RPC services are deprecated in Odoo 19. They are scheduled for removal in Odoo 22.
- Client.common¶
Expose the
commonService.Example:
Client.common.version()RPC method.Removed in Odoo 22.
- class odooly.Service(client, endpoint, methods)[source]¶
A wrapper around RPC endpoints.
The connected endpoints are exposed on the Client instance. The client argument is the connected Client. The endpoint argument is the name of the service (examples:
"object","common"). The methods is the list of methods which should be exposed on this endpoint. Usedir(...)on the instance to list them.
Environment¶
- class odooly.Env(client, db_name=())[source]¶
An environment wraps data for Odoo models and records:
To retrieve an instance of
some.model:>>> env["some.model"]
- db_name¶
Environment’s database name.
- uid¶
Environment’s user id.
- user¶
Instance of the environment’s user.
- context¶
Environment’s context dictionary. It defaults to the
langandtzof the user. UseModel.with_context()to switch the context. For exampleenv['account.invoice'].with_context({})can be used to call a method which does not accept thecontextargument.
- cr¶
Cursor on the current database.
- generate_api_key()[source]¶
Generate an API Key and configure environment to use it.
Caution: API Key is not saved. It can be set in the configuration:
api_key = ....
- session_authenticate(login=None, password=None)[source]¶
Create a Webclient session for current user.
- session_info¶
Dictionary returned when a Webclient session is authenticated. It contains
uidanduser_contextamong other user’s preferences and server parameters.
- access(model_name, mode='read')[source]¶
Check if the user has access to this model.
Optional argument mode is the access mode to check. Valid values are
read,write,createandunlink. If omitted, thereadmode is checked. Return a boolean.
- property lang¶
Return the current language code.
- models(name='', transient=False)[source]¶
Search Odoo models.
The argument name is a pattern to filter the models returned. If omitted, all models are returned.
The return value is a sorted list of model names.
- property odoo_env¶
Return a server Environment.
- property registry¶
Return the environment’s registry.
Note
When connected to the local Odoo server, the Env.odoo_env attribute grabs an Odoo Environment with the same characteristics as the Env instance (db_name, uid, context). In this case a cursor on the database is available as Env.cr.
Advanced methods¶
Those methods give more control on the Odoo objects. Please refer to the Odoo documentation for details.
- Env.execute(obj, method, *params, **kwargs)[source]¶
Wrapper around
/web/dataset/call_kwWebclient endpoint, or/json/2API endpoint orobject.execute_kwRPC method.Argument method is the name of a standard
Modelmethod or a specific method available on this obj. Method params are accepted. If needed, keyword arguments are collected in kwargs.
- Env._json2(obj, method, params, kw=None)¶
Expose the
/json/2endpoint.Added in Odoo 19.
Manage addons¶
These helpers are convenient to list, install or upgrade addons from a Python script or interactively in a Python session.
- Env.modules(name='', installed=None)[source]¶
Return a dictionary of modules.
The optional argument name is a pattern to filter the modules. If the boolean argument installed is
True, the modules which are “Not Installed” or “Not Installable” are omitted. If the argument isFalse, only these modules are returned. If argument installed is omitted, all modules are returned. The return value is a dictionary where module names are grouped in lists according to theirstate.
Note
It is not recommended to install or upgrade modules in offline mode when any web server is still running: the operation will not be signaled to other processes. This restriction does not apply when connected through Webclient API or JSON-RPC API.
Model and Records¶
The Env provides a high level API similar to the Odoo API, which
encapsulates objects into Active Records.
The Model is instantiated using the client.env[...] syntax.
Example: client.env['res.company'] returns a Model.
- class odooly.Model(client, model_name)[source]¶
The class for Odoo models.
- fields(names=None, attributes=None)[source]¶
Return a dictionary of the fields of the model.
Optional argument names is a sequence of field names or a space separated string of these names. If omitted, all fields are returned. Optional argument attributes is a sequence of attributes or a space separated string of these attributes. If omitted, all attributes are returned.
- access(mode='read')[source]¶
Check if the user has access to this model.
Optional argument mode is the access mode to check. Valid values are
read,write,createandunlink. If omitted, thereadmode is checked. Return a boolean.
- read(domain, fields=None, offset=0, limit=None, order=None)[source]¶
Wrapper for
client.execute(model, 'read', [...], ('a', 'b')).The first argument is a list of ids
[1, 3]or a single id42or a search domain.- The second argument, fields, accepts:
a single field:
'first_name'a tuple of fields:
('street', 'city')a space separated list:
'street city'a format string:
'{street} {city}'
If fields is omitted, all fields are read.
- If domain is a single id, then:
return a single value if a single field is requested.
return a string if a format spec is passed in the fields argument.
else, return a dictionary.
If domain is not a single id, the returned value is a list of items. Each item complies with the rules of the previous paragraph.
The optional keyword arguments offset, limit and order are used to restrict the search.
- get(domain)[source]¶
Return a single
Record.The argument domain accepts a single integer
idor a search domain, or an external IDxml_id. The return value is aRecordor None. If multiple records are found, aValueErroris raised.
- browse(ids)[source]¶
Return a
Recordor aRecordList.The argument ids accepts a single integer
idor a list of ids. If it is a single integer, the return value is aRecord. Otherwise, the return value is aRecordList.
- create(values)[source]¶
Create one
Recordor many.The argument values is a dictionary of values which are used to create the record. Relationship fields one2many and many2many accept either a list of ids or a RecordList or the extended Odoo syntax. Relationship fields many2one and reference accept either a Record or the Odoo syntax. It can create multiple records.
The newly created
Recordis returned, orRecordList.
- sudo(user=SUPERUSER_ID)¶
Attach to the provided user, or Superuser.
- with_context([context][, **overrides])¶
Attach to an extended context.
- class odooly.RecordList(model, ids)[source]¶
A sequence of Odoo
Record.It has a similar API as the
Recordclass, but for a list of records. The attributes of theRecordListare read-only, and they return list of attribute values in the same order. Themany2one,one2manyandmany2manyattributes are wrapped inRecordListand list ofRecordListobjects. Use the methodRecordList.writeto assign a single value to all the selected records.- read(fields=None)[source]¶
Same as
Record.read()method.Return a
RecordListif fields is the name of a singlemany2onefield, else return alist. SeeModel.read()for details.
- write(values)¶
Same as
Record.write()method.
- unlink()¶
Same as
Record.unlink()method.
- copy()[source]¶
Copy records and return
RecordList.The optional argument default is a mapping which overrides some values of the new records.
Supported since Odoo 18.
- exists()¶
Return a subset of records that exist.
- mapped(func)¶
Apply
funcon all records.
- filtered(func)¶
Select the records such that
func(rec)is true.As an alternative
funccan be a search domain (list) to search among the records.
- sorted(key=None, reverse=False)¶
Return the records sorted by
key.
- ensure_one()¶
Return the single record in this recordset.
Raise a ValueError it recordset has more records or is empty.
- union(*args)¶
Return the union of all records.
Preserve first occurence order.
- concat(*args)¶
Return the concatenation of all records.
- sudo(user=SUPERUSER_ID)¶
Attach to the provided user, or Superuser.
- with_context([context][, **overrides])¶
Attach to an extended context.
- get_metadata()¶
Same as
Record.get_metadata()method.
- _methods([name])¶
Same as
Model._methods()method.
- _external_id¶
Retrieve the External IDs of the
RecordList.Return the list of fully qualified External IDs of the
RecordList, with default value False if there’s none. If multiple IDs exist for a record, only one of them is returned.
- _keys¶
Return list of field names.
- _fields¶
Return a dictionary of the fields.
- class odooly.Record(model, id)[source]¶
A class for all Odoo records.
It maps any Odoo object. The fields can be accessed through attributes. The changes are immediately sent to the server. The
many2one,one2manyandmany2manyattributes are wrapped inRecordandRecordListobjects. These attributes support writing too. The attributes are evaluated lazily, and they are cached in the record. The Record’s cache is invalidated if any attribute is changed.- exists()¶
Return a subset of records that exist.
- get_metadata(details=True)¶
Lookup metadata about the record(s). Return dictionaries with the following keys:
id: object idcreate_uid: user who created the recordcreate_date: date when the record was createdwrite_uid: last user who changed the recordwrite_date: date of the last change to the recordxmlid: External ID to use to refer to this record (if there is one), in formatmodule.name.
- _methods([name])¶
Same as
Model._methods()method.
- _keys¶
Return list of field names.
- _fields¶
Return a dictionary of the fields.
- property _external_id¶
Retrieve the External ID of the
Record.Return the fully qualified External ID of the
Record, with default value False if there’s none. If multiple IDs exist, only one of them is returned (randomly).
- copy(default=None)[source]¶
Copy a record and return the new
Record.The optional argument default is a mapping which overrides some values of the new record.
- read(fields=None)[source]¶
Read the fields of the
Record.The argument fields accepts different kinds of values. See
Model.read()for details.
- unlink()¶
Delete the record(s) from the database.
- write(values)¶
Write the values in the record(s).
values is a dictionary of values. See
Model.create()for details.
Utilities¶
- odooly.issearchdomain(arg)[source]¶
Check if the argument is a search domain.
- Examples:
[('name', '=', 'mushroom'), ('state', '!=', 'draft')]['name = mushroom', 'state != draft'][]
- odooly.format_exception(type, value, tb, limit=None, chain=True)[source]¶
Format a stack trace and the exception information.
This wrapper is a replacement of
traceback.format_exceptionwhich formats the error and traceback received by API. If chain is True, then the original exception is printed too.
- odooly.read_config(section=None)[source]¶
Read the environment settings from the configuration file.
Config file
odooly.inicontains a section for each environment. Each section provides parameters for the connection:server,usernameand (optional)database,passwordandapi_key. As an alternative, server can be declared with 4 parameters:scheme / host / port / protocol. Default values are read from the[DEFAULT]section. If thepasswordis not set or is empty, it is requested on login. Return tuple(server, db or None, user, password or None, api_key or None). Without argument, it returns the list of configured environments.
- odooly.start_odoo_services(options=None, appname=None)[source]¶
Initialize the Odoo services.
Import the
odooPython package and load the Odoo services. The argument options receives the command line arguments forodoo. Example:['-c', '/path/to/odoo-server.conf', '--without-demo', 'all'].Return the
odoopackage.