Odoo Tools

Herramientas de utilidades integradas en Odoo

Tools

Existe un conjunto de herramientas integradas asociadas con el framework de Odoo que muchos desarrolladores o módulos de terceros suelen pasar por alto (se encuentran en el núcleo de Odoo, en odoo/tools).


config

Algunas herramientas auxiliares relacionadas con el archivo de configuración odoo.conf​ o los parámetros de configuración pasados ​​al ejecutable odoo.py​ al inicio.

from odoo.tools import config

config.get('db_name')
# 'odoo'

config.filestore(config.get('db_name'))
# '/var/lib/odoo/filestore/odoo'

config.session_dir
# '/var/lib/odoo/sessions'

config.options
{
    'addons_path': '/opt/odoo/addons',
    'auto_reload': False,
    'db_host': 'localhost',
}


convert

Asistentes de conversión. Se centran principalmente en la conversión de tipos de datos como XML y CSV específicos de Odoo, pero una de las funciones más sencillas integradas en la conversión es str2bool, que tiene muchos casos de uso comunes, especialmente al trabajar con API e integraciones.

from odoo.tools import convert

convert.str2bool('0')       # False
convert.str2bool('false')   # False
convert.str2bool('False')   # False

convert.str2bool('1')       # True
convert.str2bool('true')    # True
convert.str2bool('True')    # True


date_utils — getters

Existen algunas funciones integradas para obtener rangos y referencias a diferentes períodos de tiempo. Estas son específicas para períodos específicos, como "mes", "trimestre", "año fiscal", entre otras.

from odoo import fields
from odoo.tools import date_utils

sample_date = fields.Datetime.now()
# Assume it’s March 23, 2022

date_utils.get_month(sample_date)
# Returns the range for the first day of the month to the last

date_utils.get_quarter(sample_date)
# Returns the range for the first day of the fiscal quarter to the last

date_utils.get_quarter_number(sample_date)
# Returns the number of the current quarter

date_utils.get_fiscal_year(sample_date)
# Returns the range for the first day of the fiscal year to the last


date_utils — range helpers

Detrás de escena de las funciones getter anteriores, también tienes ayudantes de rango genéricos.

from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tools import date_utils

sample_date = fields.Datetime.now()
# Assume it’s March 23, 2022 at 14:20:10

date_utils.start_of(sample_date, 'hour')
# datetime.datetime(2022, 3, 23, 14, 0)
date_utils.start_of(sample_date, 'day')
# datetime.datetime(2022, 3, 23, 0, 0)
date_utils.start_of(sample_date, 'week')
# datetime.datetime(2022, 3, 25, 0, 0)
date_utils.start_of(sample_date, 'month')
# datetime.datetime(2022, 3, 1, 0, 0)
date_utils.start_of(sample_date, 'quarter')
# datetime.datetime(2022, 1, 1, 0, 0)
date_utils.start_of(sample_date, 'year')
# datetime.datetime(2022, 1, 1, 0, 0)

date_utils.end_of(sample_date, 'hour')
# datetime.datetime(2022, 3, 23, 14, 59, 59, 999999)
date_utils.end_of(sample_date, 'day')
# datetime.datetime(2022, 3, 23, 23, 59, 59, 999999)
date_utils.end_of(sample_date, 'week')
# datetime.datetime(2022, 3, 25, 23, 59, 59, 999999)
date_utils.end_of(sample_date, 'month')
# datetime.datetime(2022, 3, 1, 23, 59, 59, 999999)
date_utils.end_of(sample_date, 'quarter')
# datetime.datetime(2022, 1, 1, 23, 59, 59, 999999)
date_utils.end_of(sample_date, 'year')
# datetime.datetime(2022, 1, 1, 23, 59, 59, 999999)

# Example
for date in date_utils.date_range(
    start=sample_date,
    end=date_utils.add(sample_date, days=9),
    step=relativedelta(days=1)):
    print(date)
# 2022-03-23 14:23:10
# 2022-03-24 14:23:10
# 2022-03-25 14:23:10
# 2022-03-26 14:23:10
# 2022-03-27 14:23:10
# 2022-03-28 14:23:10
# 2022-03-29 14:23:10
# 2022-03-30 14:23:10


date_utils — Cálculos

Además, en date_utils hay un par de abstracciones para facilitar los cálculos de fechas simples.

from odoo import fields
from odoo.tools import date_utils

sample_date = fields.Datetime.now()
# Assume it’s March 23, 2022 at 14:20:10

date_utils.add(sample_date, days=5)
# datetime.datetime(2022, 3, 28, 14, 20, 10)
date_utils.add(sample_date, week=1)
# datetime.datetime(2022, 3, 30, 14, 20, 10)
date_utils.add(sample_date, year=1)
# datetime.datetime(2023, 3, 23, 14, 20, 10)
date_utils.add(sample_date, days=2, month=6, year=1)
# datetime.datetime(2023, 9, 25, 14, 20, 10)

date_utils.subtract(sample_date, days=5)
# datetime.datetime(2022, 3, 18, 14, 20, 10)
date_utils.subtract(sample_date, week=1)
# datetime.datetime(2022, 3, 16, 14, 20, 10)
date_utils.subtract(sample_date, year=1)
# datetime.datetime(2021, 3, 23, 14, 20, 10)
date_utils.subtract(sample_date, days=2, month=2, year=1)
# datetime.datetime(2021, 1, 21, 14, 20, 10)


float_utils

Un conjunto de ayudantes relacionados con números de punto flotante.

from odoo.tools import float_utils

float_utils.float_round(
    1.5424,
    precision_digits=2,
    rounding_method='DOWN')
# 1.54

float_utils.float_round(
    1.5424,
    precision_digits=3,
    rounding_method='UP')
# 1.543

float_utils.float_round(
    1.5424,
    precision_digits=3,
    rounding_method='HALF-UP')
# 1.542

float_utils.float_is_zero(0.04252, precision_digits=5)
# False

float_utils.float_is_zero(0.04252, precision_digits=1)
# True

float_utils.float_compare(0.042555, 0.04256, precision_digits=5)
# 0 => They are equal

float_utils.float_compare(0.042555, 0.04256, precision_digits=6)
# -1 => value1 is lower than value2


image

Conjunto de herramientas para manipular imágenes.

from odoo.tools import image

image.image_resize_image(img, size=(500, 500))
image.image_resize_and_sharpen(img, size=(500, 500))

with open('/path/to/image.png', 'w') as f:
    image.image_save_for_web(img, f)


mail

Hay diferentes ayudantes escritos para ayudar a crear correos electrónicos, pero generalmente ayudan con el análisis y la generación de HTML.

from odoo.tools import mail

mail.html_keep_url('http://google.com/')
# '<a href="http://google.com/" target="_blank">https://google.com</a>'

html = '''
<html>
    <head>
        <script src="/my/script.js"/>
    </head>
    <body>
        <p>Hello</p>
        <p>
            <a href="http://google.com/">Google</a>
        </p>
    </body>
</html>
'''

mail.html_sanitize(html)
# '<p>Hello</p><p><a href="http://google.com/">Google</a></p>'

mail.html2plaintext(html)
# A cool html email with A link to google.com. [1]
# [1] https://google.com

mail.plaintext2html(mail.html2plaintext(html))
# <p>Hello</p><p><a href="http://google.com/">Google</a></p>


misc

Utilidades diversas que resultan útiles.

from odoo.tools import misc

misc.DEFAULT_SERVER_DATE_FORMAT # '%Y-%m-%d'
misc.DEFAULT_SERVER_TIME_FORMAT # '%H:%M:%S'
misc.DEFAULT_SERVER_DATETIME_FORMAT # '%Y-%m-%d %H:%M:%S'

misc.flatten([[['a', 'b'], 'c'], 'd', ['e', [],'f']])
# ['a', 'b', 'c', 'd', 'e', 'f']

for i, el in misc.reverse_enumerate(['a', 'b', 'c']):
    print(i, el)
# 2 c
# 1 b
# 0 a

misc.topological_sort({
    'a': ['b', 'c'],
    'b': ['c'],
    'd': ['a'],
    'r': ['y'],
    'y': ['z'],
})
# ['d', 'a', 'b', 'c', 'r', 'y', 'z']

misc.scan_languages()
# Scan all languages

misc.human_size(1024 * 10)          # 10.0 KB
misc.human_size(1024 * 10000)       # 9.77 MB
misc.human_size(1024 * 10000000)    # 9.54 GB


for split in misc.split_every(iterable=['a', 'b', 'c', 'd'], n=2):
    print(split)
# ['a', 'b']
# ['c', 'd']

misc.groupby([
    {'first_name': 'John', 'last_name': 'Stewart'},
    {'first_name': 'Martha', 'last_name': 'Stewart'},
    {'first_name': 'Rod', 'last_name': 'Stewart'},
    {'first_name': 'Joe', 'last_name': 'Jackson'},
    ],key=lambda item: item['last_name'])
# {
#   'Stewart': [{'first_name': 'John', 'last_name': 'Stewart'},
#               {'first_name': 'Martha', 'last_name': 'Stewart'},
#               {'first_name': 'Rod', 'last_name': 'Stewart'}],
#   'Jackson': [{'first_name': 'Joe', 'last_name': 'Jackson'}]
# }

list(misc.unique(['a', 'b', 'c', 'a', 'b', 'c']))
# ['a', 'b', 'c']


Iniciar sesión para dejar un comentario