LasLabs

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 [[https://github.com/laslabs/server-tools/tree/release/9.0/auto_backup/auto_backup|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 {{{ lang=python 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
{{{ lang=python
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!


Posted

in

, ,

by

Tags:

Comments

2 responses to “Run external scripts inside Odoo’s environment”

  1. steelbird Avatar
    steelbird

    For Odoo 10, just replace ‘openerp’ with ‘odoo’. Works fine.

    1. Ted Salmon Avatar

      Thanks; you’re correct! I’ve updated the sample scripts.

Leave a Reply to Ted Salmon Cancel reply

Your email address will not be published. Required fields are marked *