openerp_proxy Package

core Module

This module provides some classes to simplify access to Odoo server via xmlrpc.

Example ussage of this module

>>> cl = Client('server.com', 'dbname', 'some_user', 'mypassword')
>>> sale_obj = cl['sale_order']
>>> sale_ids = sale_obj.search([('state','not in',['done','cancel'])])
>>> sale_data = sale_obj.read(sale_ids, ['name'])
>>> for order in sale_data:
...     print("%5s :    %s" % (order['id'],order['name']))
>>> product_tmpl_obj = cl['product.template']
>>> product_obj = cl['product.product']
>>> tmpl_ids = product_tmpl_obj.search([('name','ilike','template_name')])
>>> print(product_obj.search([('product_tmpl_id','in',tmpl_ids)]))

>>> db = Client('erp.host.com', 'dbname='db0', user='your_user')
>>> so = db['sale.order']
>>> order_ids = so.search([('state','=','done')])
>>> order = so.read(order_ids[0])

Also You can call any method (beside private ones starting with underscore(_)) of any model. For example following code allows to check availability of stock moves:

>>> db = session.connect()
>>> move_obj = db['stock.move']
>>> move_ids = [1234] # IDs of stock moves to be checked
>>> move_obj.check_assign(move_ids)

Ability to use Record class as analog to browse_record:

>>> move_obj = db['stock.move']
>>> move = move_obj.browse(1234)
>>> move.state
... 'confirmed'
>>> move.check_assign()
>>> move.refresh()
>>> move.state
... 'assigned'
>>> move.picking_id
... R('stock.picking', 12)['OUT-12']
>>> move.picking_id.id
... 12
>>> move.picking_id.name
... 'OUT-12'
>>> move.picking_id_.state
... 'assigned'
class openerp_proxy.core.Client(host, dbname=None, user=None, pwd=None, port=8069, protocol='xml-rpc', **extra_args)[source]

Bases: extend_me.Extensible

A simple class to connect to Odoo instance via RPC (XML-RPC, JSON-RPC) Should be initialized with following arguments:

Parameters:
  • host (str) – server host name to connect to
  • dbname (str) – name of database to connect to
  • user (str) – username to login as
  • pwd (str) – password to log-in with
  • port (int) – port number of server
  • protocol (str) – protocol used to connect. To get list of available protcols call: openerp_proxy.connection.get_connector_names()

any other keyword arguments will be directly passed to connector

Example:

>>> db = Client('host', 'dbname', 'user', pwd = 'Password')
>>> cl = Client('host')
>>> db2 = cl.login('dbname', 'user', 'password')

Allows access to Odoo objects / models via dictionary syntax:

>>> db['sale.order']
    Object ('sale.order')
clean_caches()[source]

Clean client related caches

connect(**kwargs)[source]

Connects to the server

if any keyword arguments will be passed, new Proxy instnace will be created using folowing algorithm: get init args from self instance and update them with passed keyword arguments, and call Proxy class constructor passing result as arguments.

Note, that if You pass any keyword arguments, You also should pass ‘pwd’ keyword argument with user password

Returns:Id of user logged in or new Client instance (if kwargs passed)
Return type:int|Client
Raises LoginException:
 if wrong login or password
connection

Connection to server.

Return type:openerp_proxy.connection.connection.ConnectorBase
database_version

Base database version (‘8.0’, ‘9.0’, etc)

(Already parsed with pkg_resources.parse_version)

database_version_full

Full database base version (‘9.0.1.3’, etc)

(Already parsed with pkg_resources.parse_version)

dbname

Name of database to connect to

Return type:str
execute(obj, method, *args, **kwargs)[source]

Call method method on object obj passing all next positional and keyword (if available on server) arguments to remote method

Note that passing keyword argments not available on OpenERp/Odoo server 6.0 and older

Parameters:
  • obj (string) – object name to call method for
  • method (string) – name of method to call
Returns:

result of RPC method call

execute_wkf(object_name, signal, object_id)[source]

Triggers workflow event on specified object

Parameters:
  • object_name (string) – send workflow signal for
  • signal (string) – name of signal to send
  • object_id – ID of document (record) to send signal to
classmethod from_url(url)[source]

Create Client instance from URL

Parameters:url (str) – url of Client
Returns:Client instance
Return type:Client
get_init_args()[source]

Returns dictionary with init arguments which can be safely passed to class constructor

Return type:dict
get_obj(object_name)[source]

Returns wraper around Odoo object ‘object_name’ which is instance of orm.object.Object class

Parameters:object_name – name of an object to get wraper for
Returns:instance of Object which wraps choosen object
Return type:openerp_proxy.orm.object.Object
get_url()[source]

Returns dabase URL

At this moment mostly used internaly in session

host

Server host

Return type:str
login(dbname, user, password)[source]

Login to database

Return new Client instance. (Just an aliase on connect method)

Parameters:
  • dbname (str) – name of database to connect to
  • user (str) – username to login as
  • password (str) – password to log-in with
Returns:

new Client instance, with specifed credentials

Return type:

openerp_proxy.core.Client

plugins

Plugins associated with this Client instance

Return type:openerp_proxy.plugin.PluginManager

Usage examples:

db.plugins.module_utils    # access module_utils plugin
db.plugins['module_utils]  # access module_utils plugin
port

Server port

protocol

Server protocol

Return type:str
reconnect()[source]

Recreates connection to the server and clears caches

Returns:ID of user logged in
Return type:int
Raises ClientException:
 if wrong login or password
ref(xmlid)[source]

Return record for specified xmlid

Parameters:xmlid (str) – string representing xmlid to get record for. xmlid must be fully qualified (with module name)
Returns:Record for that xmlid or False
Return type:openerp_proxy.orm.record.Record
registered_objects

List of registered in Odoo database objects

Return type:list
server_version

Server base version (‘8.0’, ‘9.0’, etc)

(Already parsed with pkg_resources.parse_version)

services

ServiceManager instance, which contains list of all available services for current connection.

Return type:openerp_proxy.service.service.ServiceManager

Usage examples:

db.services.report   # report service
db.services.object   # object service (model related actions)
db.services.common   # used for login
                     # (db.services.common.login(dbname,
                     #                           username,
                     #                           password)
db.services.db       # database management service
classmethod to_url(inst, **kwargs)[source]

Converts instance to url

Parameters:inst (Client|dict) – instance to convert to init args
Returns:generated URL
Return type:str
uid

Returns ID of current user. if one is None, connects to database and returns it

Return type:int
user

Currenct logged in user instance

Return type:openerp_proxy.orm.record.Record
user_context

Get current user context

Return type:dict
username

User login used to access DB

Return type:str

session Module

class openerp_proxy.session.Session(data_file='~/.openerp_proxy.json')[source]

Bases: extend_me.Extensible, openerp_proxy.utils.DirMixIn

Simple session manager which allows to manage databases easier This class stores information about databases You used in home directory, and on init it loads history and allows simply connect to database by url or index. No more hosts, usernames, ports, etc... required to be memorized. Just on session start call:

>>> print(session)

And You will get all databases You worked with listed as (index, url) pairs. To connect to one of thouse databases just call session[index|url] and required Client object will be returned.

Parameters:data_file (string) – path to session file
add_db(db)

Add db to session.

Parameters:db (openerp_proxy.core.Client) – database (client instance) to be added to session
add_path(path)

Adds extra path to python import path.

Parameters:path (string) – Paths to be added
Returns:None

Note: this way path will be saved in session

aliase(name, val)

Sets up aliase ‘name’ for val

Parameters:
  • name (string) – new aliase
  • val (int|string|Client instance) – database to create aliase for

val could be index, url or Client object:

session.aliase('tdb', 1)
session.aliase('mdb', 'xml-rpc://me@my.example.com:8069/my_db')
session.aliase('xdb', db)

And now You can use this aliase like:

session.tdb
session.mdb
session.xdb
Returns:unchanged val
aliases

List of database aliases

To add new database aliase, use method aliase:

session.aliase('mdb', db)  # db is instance of Client
connect(host=None, dbname=None, user=None, pwd=None, port=8069, protocol='xml-rpc', interactive=True, no_save=False)

Wraper around Client constructor class to simplify connect from shell.

Parameters:
  • host (str) – host name to connect to (will be asked interactvely if not provided)
  • dbname (str) – name of database to connect to (will be asked interactvely if not provided)
  • user (str) – user name to connect as (will be asked interactvely if not provided)
  • pwd (str) – password for selected user (will be asked interactvely if not provided)
  • port (int) – port to connect to. (default: 8069)
  • interactive (bool) – ask for connection parameters if not provided. (default: True)
  • no_save (bool) – if set to True database will not be saved to session
Returns:

Client object

db_list

Returns list of URLs of databases available in current session

Returns:list of urls of databases from session
Return type:list of strings
del_db(db)

Remove database from session

Parameters:db (openerp_proxy.core.Client) – database (client instance) to be removed from session
extra_paths

List of extra pyhton paths, used by this session

get_db(url_or_index)

Returns instance of Client object, that represents single Odoo database it connected to, specified by passed index (integer) or url (string) of database, previously saved in session.

Parameters:url_or_index (int|string) – must be integer (if index) or string (if url). this parametr specifies database to get from session
Returns:Client instance
Raises ValueError:
 if cannot find database by specified args

Examples:

session.get_db(1)   # using index
session.get_db('xml-rpc://katyukha@erp.jbm.int:8069/jbm0')
session.get_db('my_db')   # using aliase
index

Property which returns dict with {index: url}

index_rev

Reverse index.

Property which returns dict with {url: index}

option(opt, val=None, default=None)

Get or set option. if val is passed, val will be set as value for option, else just option value will be returned

Parameters:
  • opt (str) – option to get or set value for
  • val – value to be set for option opt
Returns:

value of option opt

Currently available options:

  • store_passwords (bool) If set to True then all used passwords will be stored on session.save. But be careful, because of encription used for stored passwords is very week.
save()

Saves session on disk

start_up_imports

List of start-up imports

If You want some module to be automaticaly imported on when session starts, that just add it to this list:

session.start_up_imports.append('openerp_proxy.ext.sugar')

exceptions Module

exception openerp_proxy.exceptions.ClientException[source]

Bases: openerp_proxy.exceptions.Error

Base class for client related exceptions

exception openerp_proxy.exceptions.ConnectorError[source]

Bases: openerp_proxy.exceptions.Error

Base class for exceptions related to connectors

exception openerp_proxy.exceptions.Error[source]

Bases: exceptions.Exception

Base class for exceptions

exception openerp_proxy.exceptions.LoginException[source]

Bases: openerp_proxy.exceptions.ClientException

This exception should be raised, when operations requires login and password. For example interaction with Odoo object service.

exception openerp_proxy.exceptions.ObjectException[source]

Bases: openerp_proxy.exceptions.ClientException

Base class for exceptions related to Objects

exception openerp_proxy.exceptions.ReportError[source]

Bases: openerp_proxy.exceptions.Error

Error raise in process of report generation

plugin Module

class openerp_proxy.plugin.Plugin(client)[source]

Bases: object

Base class for all plugins, extensible by name

(uses metaclass extend_me.ExtensibleByHashType)

Parameters:client (openerp_proxy.core.Client instance) – instance of Client to bind plugins to

Example of simple plugin:

from openerp_proxy.plugin import Plugin

class AttandanceUtils(Plugin):

    # This is required to register Your plugin
    # *name* - is for db.plugins.<name>
    class Meta:
        name = "attendance"

    def get_sign_state(self):
        # Note: folowing code works on version 6 of Openerp/Odoo
        emp_obj = self.client['hr.employee']
        emp_id = emp_obj.search(
            [('user_id', '=', self.client.uid)])
        emp = emp_obj.read(emp_id, ['state'])
        return emp[0]['state']

This plugin will automaticaly register itself in system, when module which contains it will be imported.

client

Related Client instance

class openerp_proxy.plugin.PluginManager(client)[source]

Bases: extend_me.Extensible, openerp_proxy.utils.DirMixIn

Class that holds information about all plugins

Parameters:client (openerp_proxy.core.Client instance) – instance of Client to bind plugins to

Plugiins will be accessible via index or attribute syntax:

plugins = PluginManager(client)
plugins.Test   # acceps plugin 'Test' as attribute
plugins['Test']  # access plugin 'Test' via indexing
refresh()[source]

Clean-up plugin cache This will force to reinitialize each plugin when asked

registered_plugins

List of names of registered plugins

class openerp_proxy.plugin.TestPlugin(client)[source]

Bases: openerp_proxy.plugin.Plugin

Jusn an example plugin to test if plugin logic works

class Meta[source]
name = 'Test'
TestPlugin.test()[source]

utils Module

class openerp_proxy.utils.AttrDict[source]

Bases: dict, openerp_proxy.utils.DirMixIn

Simple class to make dictionary able to use attribute get operation to get elements it contains using syntax like:

>>> d = AttrDict(arg1=1, arg2='hello')
>>> print(d.arg1)
    1
>>> print(d.arg2)
    hello
>>> print(d['arg2'])
    hello
>>> print(d['arg1'])
    1
class openerp_proxy.utils.DirMixIn[source]

Bases: object

Mix-in to make implementing __dir__ method in subclasses simpler

class openerp_proxy.utils.UConverter(hint_encodings=None)[source]

Bases: object

Simple converter to unicode

Create instance with specified list of encodings to be used to try to convert value to unicode

Example:

ustr = UConverter(['utf-8', 'cp-1251'])
my_unicode_str = ustr(b'hello - привет')
default_encodings = ['utf-8', 'ascii']
openerp_proxy.utils.wpartial(func, *args, **kwargs)[source]

Wrapped partial, same as functools.partial decorator, but also calls functools.wrap on its result thus shwing correct function name and representation.

openerp_proxy.utils.makedirs(path)[source]

os.makedirs wrapper. No errors raised if directory already exists

Parameters:path (str) – directory path to create
openerp_proxy.utils.json_read(file_path)[source]

Read specified json file

openerp_proxy.utils.json_write(file_path, *args, **kwargs)[source]

Write data to specified json file

Note, this function uses dumps function to convert data to json first, and write only if conversion is successfule. This allows to avoid loss of data when rewriting file.