I am working with the Odoo XML-RPC API and I want to reuse a connection (ServerProxy object) across multiple functions in my package.
Current Setup
I establish the connection like this:
import xmlrpc.client import pprint # Demo connection to Odoo info = xmlrpc.client.ServerProxy('https://demo.odoo.com/start').start() url, db, username, password = info['host'], info['database'], info['user'], info['password'] print(f"Connecting to Odoo at {url}, database: {db}, user: {username}") # Real data for actual operations from my_package.core.config import odoo_url, odoo_db, odoo_username, odoo_password common = xmlrpc.client.ServerProxy(f'{odoo_url}/xmlrpc/2/common') uid = common.authenticate(odoo_db, odoo_username, odoo_password, {}) models = xmlrpc.client.ServerProxy(f'{odoo_url}/xmlrpc/2/object') pprint.pprint(common.version()) print('uid =', uid) print('models =', models) output:
Connecting to Odoo at https://demo4.odoo.com, database: demo_saas-182_6bcd3971f542_1745421877, user: admin {'protocol_version': 1, 'server_serie': '17.0', 'server_version': '17.0+e', 'server_version_info': [17, 0, 0, 'final', 0, 'e']} uid = 21 models = <ServerProxy for dtsc.odoo.com/xmlrpc/2/object> What I Want to Achieve
I want to connect to the Odoo server once and reuse the models object in different functions across my package, so I avoid reconnecting every time.
Instead of doing this in each function:
# Reconnect every time (current approach) common = xmlrpc.client.ServerProxy(f'{odoo_url}/xmlrpc/2/common') uid = common.authenticate(odoo_db, odoo_username, odoo_password, {}) models = xmlrpc.client.ServerProxy(f'{odoo_url}/xmlrpc/2/object') # Do something I want to do something like this:
# my_package/core/my_file.py def my_function(models): # Use the existing ServerProxy object information = do_something_with(models) return information ... # main.py from my_package.core.my_file import my_function update_information = my_function(models) # Pass the connected models object My Question
How can I best structure my code to pass the ServerProxy object (or other related objects like uid) into my functions for reuse?
Should I pass multiple objects (models, uid, etc.) into each function, or is there a better way to encapsulate this connection logic (e.g., using a class or context manager)?
Would you use a class or a context manager?
Any best practices for this kind of setup with Odoo’s XML-RPC API would be appreciated!
thanks!