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 an odoo Python 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 connected Client.

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_US and 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 parse odooly.ini file, where it searches for the section [ <environment> ].

See read_config() for details of the configuration file format.

Client.env

Current Env environment of the client.

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.

Client.database

Expose the /web/database WebAPI.

Example: Client.database.list() method.

Client.web

Expose the root /web WebAPI.

Client.web_dataset

Expose the /web/dataset WebAPI.

Client.web_session

Expose the /web/session WebAPI.

Client.web_webclient

Expose the /web/webclient WebAPI.

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. Use dir(...) on the instance to list them.

class odooly.Json2(client, database, api_key)[source]

A connection to Json-2 API

Added in Odoo 19.

__call__(model, method, args, kw=None)[source]

Execute API call on the model.

doc(model)[source]

Documentation of the model.

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 common Service.

Example: Client.common.version() RPC method.

Removed in Odoo 22.

Client._object

Expose the object Service.

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. Use dir(...) on the instance to list them.

Environment

class odooly.Env(client, db_name=())[source]

An environment wraps data for Odoo models and records:

  • db_name, the current database;

  • uid, the current user id;

  • context, the current context dictionary.

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 lang and tz of the user. Use Model.with_context() to switch the context. For example env['account.invoice'].with_context({}) can be used to call a method which does not accept the context argument.

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 = ....

set_api_key(api_key, store=True)[source]

Configure methods to use an API key.

session_authenticate(login=None, password=None)[source]

Create a Webclient session for current user.

session_destroy()[source]

Terminate current Webclient session.

session_info

Dictionary returned when a Webclient session is authenticated. It contains uid and user_context among other user’s preferences and server parameters.

sudo(user=SUPERUSER_ID)[source]

Attach to the provided user, or Superuser.

__getitem__(name)[source]

Return the Model for the given name.

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, create and unlink. If omitted, the read mode 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.

ref(xml_id)[source]

Return the record for the given xml_id external ID.

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_kw Webclient endpoint, or /json/2 API endpoint or object.execute_kw RPC method.

Argument method is the name of a standard Model method or a specific method available on this obj. Method params are accepted. If needed, keyword arguments are collected in kwargs.

Env.sql(queries)[source]

Execute SQL commands on the PostgreSQL server.

Env._call_kw(obj, method, params, kw=None)[source]

Expose the /web/dataset/call_kw endpoint.

Env._json2(obj, method, params, kw=None)

Expose the /json/2 endpoint.

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 is False, 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 their state.

Env.install(*modules, quiet=False)[source]

Press button Install.

Env.upgrade(*modules, quiet=False)[source]

Press button Upgrade.

Env.uninstall(*modules, quiet=False)[source]

Press button Uninstall.

Env.upgrade_cancel()[source]

Press button Cancel Upgrade/Install/Uninstall.

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.

keys()[source]

Return the keys of the model.

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.

field(name)[source]

Return the field properties for field name.

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, create and unlink. If omitted, the read mode is checked. Return a boolean.

search(domain, offset=0, limit=None, order=None)[source]

Search for records in the domain.

search_count(domain)[source]

Count the records in the domain.

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 id 42 or 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 id or a search domain, or an external ID xml_id. The return value is a Record or None. If multiple records are found, a ValueError is raised.

browse(ids)[source]

Return a Record or a RecordList.

The argument ids accepts a single integer id or a list of ids. If it is a single integer, the return value is a Record. Otherwise, the return value is a RecordList.

create(values)[source]

Create one Record or 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 Record is returned, or RecordList.

with_env(env)[source]

Attach to the provided environment.

sudo(user=SUPERUSER_ID)

Attach to the provided user, or Superuser.

with_context([context][, **overrides])

Attach to an extended context.

_get_external_ids(ids=None)[source]

Retrieve the External IDs of the records.

Return a dictionary with keys being the fully qualified External IDs, and values the Record entries.

_methods([name])[source]

List methods and arguments.

Argument name is a pattern to filter the methods returned. If omitted, all methods are returned.

class odooly.RecordList(model, ids)[source]

A sequence of Odoo Record.

It has a similar API as the Record class, but for a list of records. The attributes of the RecordList are read-only, and they return list of attribute values in the same order. The many2one, one2many and many2many attributes are wrapped in RecordList and list of RecordList objects. Use the method RecordList.write to assign a single value to all the selected records.

read(fields=None)[source]

Same as Record.read() method.

Return a RecordList if fields is the name of a single many2one field, else return a list. See Model.read() for details.

write(values)

Same as Record.write() method.

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 func on all records.

filtered(func)

Select the records such that func(rec) is true.

As an alternative func can 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.

with_env(env)[source]
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, one2many and many2many attributes are wrapped in Record and RecordList objects. 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 id

  • create_uid: user who created the record

  • create_date: date when the record was created

  • write_uid: last user who changed the record

  • write_date: date of the last change to the record

  • xmlid: External ID to use to refer to this record (if there is one), in format module.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.

refresh()[source]

Force refreshing the record’s data.

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.searchargs(params, kwargs=None)[source]

Compute the ‘search’ parameters.

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_exception which 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.ini contains a section for each environment. Each section provides parameters for the connection: server, username and (optional) database, password and api_key. As an alternative, server can be declared with 4 parameters: scheme / host / port / protocol. Default values are read from the [DEFAULT] section. If the password is 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 odoo Python package and load the Odoo services. The argument options receives the command line arguments for odoo. Example:

['-c', '/path/to/odoo-server.conf', '--without-demo', 'all'].

Return the odoo package.