Run external scripts inside Odoo’s environment
You may run into a situation where you want to script actions in Odoo but do not necessarily want to run them within Odoo or its shell. To this end, we have devised a way to load and interact with the Odoo environment within a Python script. Our use case was a slow executing backup process that we wanted to run via the system cron.
In order for the script to work, you need to specify the directory where your Odoo config exists as well as the database to use. With those data points, we can load all add-ons and create our environment. See the code below in all its glory to get started!
For versions <= 9.0
import openerp DB_NAME = ‘test’ ODOO_CONF = ‘/etc/odoo/odoo.conf’ UID = openerp.SUPERUSER_ID openerp.tools.config.parse_config([‘–config=%s’ % ODOO_CONF]) with openerp.api.Environment.manage(): registry = openerp.modules.registry.RegistryManager.get(DB_NAME) with registry.cursor() as cr: # Load our context and environment given the database cursor and UID ctx = openerp.api.Environment(cr, UID, {})[‘res.users’].context_get() env = openerp.api.Environment(cr, UID, ctx) # After loading the database, run the backup method model = env[‘db.backup’] model.action_backup_all() try: cr.commit() except Exception: cr.rollback() raise
For versions >= 10.0
import odoo DB_NAME = 'test' ODOO_CONF = '/etc/odoo/odoo.conf' UID = odoo.SUPERUSER_ID odoo.tools.config.parse_config(['--config=%s' % ODOO_CONF]) with odoo.api.Environment.manage(): registry = odoo.modules.registry.RegistryManager.get(DB_NAME) with registry.cursor() as cr: # Load our context and environment given the database cursor and UID ctx = odoo.api.Environment(cr, UID, {})['res.users'].context_get() env = odoo.api.Environment(cr, UID, ctx) # After loading the database, run the backup method model = env['db.backup'] model.action_backup_all() try: cr.commit() except Exception: cr.rollback() raise
Make sure you run your newly created script is using the same python binary that Odoo is executed with!
1
For Odoo 10, just replace ‘openerp’ with ‘odoo’. Works fine.
Thanks; you’re correct! I’ve updated the sample scripts.