26. Desarrollando con Odoo (21). IMPORTANTE: Entorno de desarrollo. Recapitulaciones del capítulo 8 (Development, Test and Debug).

1. Instalar Postgres

Nos basamos en el libro de David Reis
Para ello actualizamos el sistema, instalamos postgres, asignamos nuestro usuario como super usuario de la BD y arrancamos el servicio de postgres
"env": {"PYTHONPATH":"${workspaceRoot}"},  // modify PYTHONPATH
#1. Instalar Postgres
sudo apt update 
sudo apt install postgresql

#2. Hacer nuestro usuario DB Superuser
sudo su -c "createuser -s $USER" postgres

#3. Arrancar el servicio de postgres
sudo service postgresql start


2. Instalar las dependencias de Odoo

Nos basamos en el libro de David Reis
Instalamos librerías, node, y less

Instalamos tambien wkhtmltopdf

#1. Instalar Git
sudo apt update
sudo apt install git  

#2. Instalar python v.3
sudo apt install python3-dev python3-pip python3-wheel python3-venv 

#3. Instalamos dependencias del S.O.
sudo apt install \ 
  build-essential \
  libpq-dev \ 
  libxslt-dev \ 
  libzip-dev \ 
  libldap2-dev \ 
  libsasl2-dev \
  libssl-dev 

#4. Instalamos node.js 
sudo apt install npm

#5. Instalamos less 
sudo npm install -g less less-plugin-clean-css

#6. Instalamos wkhtmltopdf
sudo apt install wkhtmltopdf


3. Instalar Odoo desde el codigo fuente

Nos basamos en el libro de David Reis
Creamos una carpeta de trabajo en my caso "~/MyPython/prova01", creamos un entorno virtual de python en dicha carpeta y lo activamos. Actualizamos pip.
Clonamos el repositorio de Odoo16 en el 1er nivel, 
Instalamos las dependencias del fichero requirements.txt
Instalamos Odoo

#1. Crear carpeta de trabajo y nos situamos en ella
mkdir ~/MyPython/prova01
#   Abrir dicha carpeta en VSCode y acceder a la pantalla de terminal 
#   Comprobando que estamos en dicha pantalla. 
#   Si no lo estamos, teclear:
cd ~/MyPython/prova01

#   A partir de aquí vamos a continuar con el terminal de vscode


#2. Crear entorno virtual
python3 -m venv ~/MyPython/prova01/env16

#3. Activar entorno virtual
source ~/MyPython/prova01/env16/bin/activate

#4. Ahora debe aparecer env16 a la izquierda de la línea de comandos
#   Actualizamos pip
pip install -U pip

#5. Descargamos Odoo 16 en 1er nivel del repositorio (con -b seleccionamos la versión
git clone https://github.com/odoo/odoo.git -b 16.0 --depth=1

#6. Actualizamos las librerías python que se indican en el fivhero requirements.txt
pip install -r ~/MyPython/prova01/odoo/requirements.txt

#7. Instalamos Odoo propiamente dicho
pip install -e ~/MyPython/prova01/odoo

#8. Crear una configuración de Odoo mediante su ejecución. 
#   Cuando se ejecuta la primera vez sin pasar parámetros
#    se crea una configuración en ~/.odoorc
#    pero ahora creamos una en ~/MyPython/prova01/odoo16.conf
odoo -c ~/MyPython/prova01/odoo16.conf --save --stop
 

Veamos el fichero generado odoo16.conf y en concreto la variable data_dir cuyo valor es:

/home/ximo/.local/share/Odoo

Y vamos a crear un carpeta ~/MyPython/prova01/odoo/my-data

y copiamos el contenido de /home/ximo/.local/share/Odoo a esta carpeta

#   Ir a la carpeta origen
cd ~/.local/share/Odoo
#   Copiamos a la otra carpeta
cp -r * ~/MyPython/prova04/odoo/my-data 

Y cambiamos el contenido de la variable anterior en el fichero odoo16.conf

#data_dir = /home/eduard/.local/share/Odoo
data_dir = /home/eduard/MyPython/prova01/my-data

4. Crear una configuración de depuración en VSCode

Me he basado fundamentalmente en Cybrosys.
Hay que verificar que la extensión para Python y depuración de Python (debugpy) (ambas de Microsoft) estém instaladas. Es conveniente instalar Codeium pues sugiere muy bien el código  escribir y ayuda a documentar.
Ejecutamos el botón del triangulito con una cucaracha y seleccionamos Python Debugger: Current File with arguments y le damos al botton del engranaje. 


Nos propone un fichero launch.json (que guarda dentro de la carpeta .vscode) pero que debemos cambiar por este otro

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "ODOO: Python Debugger: Current File with Arguments",
      "type": "debugpy",
      "request": "launch",
      //"program": "/home/ximo/MyPython/prova01/odoo/odoo-bin",
      "program": "${workspaceFolder}/odoo/odoo-bin", 
      "console": "integratedTerminal",
      //"args": ["--config=/home/ximo/MyPython/prova01/odoo16.conf"]
      "args": ["--config=${workspaceFolder}/odoo16.conf"]
    }
  ]
}

Si ahora ejecutamos Run - Run without debuging o apretamos Crtl + F5 arrancará rápidamente odoo y podremos ver la pantalla que nos pide que indiquemos la BD


Si por el contrario ejecutamos con Start Debugging (F5), arranca más despació.... pero nos permite hacer paradas de código y comprobar las variables.

4.1. Crear nuestra carpeta desarrollo independiente.

Ahora paramos la ejecución de Odoo.

Creamos la carpeta ~/MyPython/prova01/my-addons que será donde guardemos nuestros módulos y modificamos el fichero de configuración anteriormente creado odoo16.conf y añadimos esta carpeta a la lista de carpetas de addons:

[options]
addons_path = /home/ximo/MyPython/prova01/my-addons,/home/eduard/MyPython/prova01/odoo/odoo/addons,/home/eduard/MyPython/prova01/odoo/addons
admin_passwd = $pbkdf2-........

4.2. Eliminar los errores de vscode que no encuentra las dependencias

1. Primero eliminamos el error que se queja el pylance C0114 que no encuentra un docstring en el  módulo. Para ello creamos un comentario como el que se muesta en el ejemplo. Ver documentación de pylint.

"""To remove docstring complaits C0114"""

from odoo import api, fields, exceptions, models

class Checkout(models.Model):



2. Para que reconozca las librería de Odoo hay que modificar un poco lo que dice Angel Adan Ramirez Isea y vamos al menú de VSCode:
Archivo (File) - Preferencias (Preferences) - Configuración (Settings)
Ahora tecleamos import


Elegimos Python



Y hacemos click sobre Editar en settings.json




 Y añadimos la ruta a la carpeta de odoo dentro de python.autoComplete.extraPaths y  python.analysis.extraPaths






4.3. Depuració opcional de Daniel Reis

Propone instalar watchdog para que recargue odoo cada vez que hay cambios
(env16) $ pip install watchdog

Propone ejecutar odoo con la opción --dev=all o (--dev=OPTIONS siendo options all, [pudb|wdb|ipdb|pdb], reload, qweb,werkzeug, y xml.)

Con el depurador por omisión (pdb) en una línea cualquiera del código se introduce 
import pdb; pdb.set_trace()

Y a partir de ahí se pueden utilizar estos comandos en la consola de sistema operativo donde se ejecuta:
• h (help) displays a summary of the available pdb commands.
• p (print) evaluates and prints an expression.
• pp (pretty-print) is useful to print data structures, such as dictionaries or lists.
• l (list) lists the code around the instruction to be executed next.
• n (next) steps over to the next instruction.
• s (step) steps into the current instruction.
• c (continue) continues execution normally.
• u (up) moves up in the execution stack.
• d (down) moves down in the execution stack.
• bt (backtrace) shows the current execution stack.

Para mas información ver 

Para el caso de vscode podemos modificar el launch.json añadiendo el --dev=all en el campo args


{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "ODOO: Python Debugger: Current File with Arguments",
      "type": "debugpy",
      "request": "launch",
      //"program": "/home/ximo/MyPython/prova01/odoo/odoo-bin",
      "program": "${workspaceFolder}/odoo/odoo-bin", 
      "console": "integratedTerminal",
      //"args": ["--config=/home/ximo/MyPython/prova01/odoo16.conf"]
      "args": [
        "--config=${workspaceFolder}/odoo16.conf",
        "--dev=all"
      ]
    }
  ]
}

Y ejecutamos Crtl-F5 (Run without debugging) y rápidamente se para en dicha línea y podemos utilizar el debugger.

La ventaja de este modo de depuración es que es mucho más rápido de ejecutar.

5. Crear tests (banco de pruebas)

Del libro de Daniel Resi y Cybrosys

1. Crear la carpeta tests dentro de la aplicación

2. Referenciar dicho test en el fichero tests/__init__.py por ejemplo para test_book.py
    from . import test_book

3. Crear las clases usando cualquiera de estas clases básiscas de depuración:
    odoo.tests.common.TransactionCase  (para separar cada test en su propia transacción)
    odoo.tests.common.SingleTransactionCase (todos los tests compartiendo transacción)
    odoo.tests.common.HttpCase
    odoo.tests.common.SavepointCase

4. Se definen al menos 2 métodos:
    def setUp(self, *args, **kwargs): Que crea datos y variables
    def test_XXXXXXXX(self):  Para la prueba en si, contiene instrucciones "assert"

5. Las funciones tipo assert mas utilizadas son (Cybrosys)
    assertEqual(arg1, arg2, msg=None)
    assertNotEqual(arg1, arg2, msg = None)
    assertTrue(expression, msg = None)
    assertFalse(expression, msg = None)
    assertIsNone(expression, msg = None)
    assertIsNotNone(expression, msg = None)
    assertIsInstance(object, class, msg = None) 
    assertNotIsInstance(object, class, msg = None) 
    assertIn(arg1, arg2, msg = None)
    assertNotIn(arg1, arg2, msg = None)
    assertIs(arg1, arg2, msg = None)
    assertIsNot(arg1, arg2, msg = None)

5. Se ejecutaran los tests mediante
    ./odoo-bin -i {module_to_install} --test-enable -c {conf path}
    por ejemplo  ./odoo-bin -i automated_test_demo --test-enable -c /odoo.conf

    y si queremos ejecutarlo con vscode aprovechando el launch.json, podemos modificar este así:

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "ODOO: Python Debugger: Current File with Arguments",
      "type": "debugpy",
      "request": "launch",
      //"program": "/home/ximo/MyPython/prova01/odoo/odoo-bin",
      "program": "${workspaceFolder}/odoo/odoo-bin", 
      "console": "integratedTerminal",
      //"args": ["--config=/home/ximo/MyPython/prova01/odoo16.conf"]
      "args": [
        "--config=${workspaceFolder}/odoo16.conf",
        "--init=automated_test_demo"
        "--test_enable"
      ]
    }
  ]
}

  Y ejecutamos Crt-F5 (Run without debugging) 

6. Curiosidades opcionales

Del libro de Danies Reis

6.1 Manejo de BD.


#1. Creadr DB desde la línea de comandos
(env16) $ odoo -d new-db --stop-after-init

#2. Lo mismo 
createdb new-db2

#3. Copiar BD
createdb --template=new-db new-db3

#4. Listar las bases de datos
psql -l

#5. Borrar una BD
dropdb new-db3


6.2 Configurar Odoo por línea de comandos.


#1. Ayuda
odoo --help

#2. Crear la configuración ~/.odoorc
odoo --save --stop-after-init

#3. Crar una nueva configuración en un fichero
odoo -c fichero --save --stop-after-init

#4. Cambiar el puerto de escucha http
odoo --http-port=8071
odoo -p 8071
#5. Filtrar las BD que podemos acceder odoo --db-filter=^new-db$
#6. Instala los módulos (separados por comas)
odoo -d mydb --init=module1,module2
odoo -d mydb -i moduile1,module2


#6. Cambiar el log
odoo --log-level=debug_sql –logfile=fichero

6.3 Resultado de ejecutar odoo -h.


Usage: odoo server [options]

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit

  Common options:
    -c CONFIG, --config=CONFIG
                        specify alternate config file
    -s, --save          save configuration to ~/.odoorc (or to
                        ~/.openerp_serverrc if it exists)
    -i INIT, --init=INIT
                        install one or more modules (comma-separated list, use
                        "all" for all modules), requires -d
    -u UPDATE, --update=UPDATE
                        update one or more modules (comma-separated list, use
                        "all" for all modules). Requires -d.
    --without-demo=WITHOUT_DEMO
                        disable loading demo data for modules to be installed
                        (comma-separated, use "all" for all modules). Requires
                        -d and -i. Default is none
    -P IMPORT_PARTIAL, --import-partial=IMPORT_PARTIAL
                        Use this for big data importation, if it crashes you
                        will be able to continue at the current state. Provide
                        a filename to store intermediate importation states.
    --pidfile=PIDFILE   file where the server pid will be stored
    --addons-path=ADDONS_PATH
                        specify additional addons paths (separated by commas).
    --upgrade-path=UPGRADE_PATH
                        specify an additional upgrade path.
    --load=SERVER_WIDE_MODULES
                        Comma-separated list of server-wide modules.
    -D DATA_DIR, --data-dir=DATA_DIR
                        Directory where to store Odoo data

  HTTP Service Configuration:
    --http-interface=HTTP_INTERFACE
                        Listen interface address for HTTP services. Keep empty
                        to listen on all interfaces (0.0.0.0)
    -p PORT, --http-port=PORT
                        Listen port for the main HTTP service
    --longpolling-port=PORT
                        Deprecated alias to the gevent-port option
    --gevent-port=PORT  Listen port for the gevent worker
    --no-http           Disable the HTTP and Longpolling services entirely
    --proxy-mode        Activate reverse proxy WSGI wrappers (headers
                        rewriting) Only enable this when running behind a
                        trusted web proxy!
    --x-sendfile        Activate X-Sendfile (apache) and X-Accel-Redirect
                        (nginx) HTTP response header to delegate the delivery
                        of large files (assets/attachments) to the web server.

  Web interface Configuration:
    --db-filter=REGEXP  Regular expressions for filtering available databases
                        for Web UI. The expression can use %d (domain) and %h
                        (host) placeholders.

  Testing Configuration:
    --test-file=TEST_FILE
                        Launch a python test file.
    --test-enable       Enable unit tests.
    --test-tags=TEST_TAGS
                        Comma-separated list of specs to filter which tests to
                        execute. Enable unit tests if set. A filter spec has
                        the format: [-][tag][/module][:class][.method] The '-'
                        specifies if we want to include or exclude tests
                        matching this spec. The tag will match tags added on a
                        class with a @tagged decorator (all Test classes have
                        'standard' and 'at_install' tags until explicitly
                        removed, see the decorator documentation). '*' will
                        match all tags. If tag is omitted on include mode, its
                        value is 'standard'. If tag is omitted on exclude
                        mode, its value is '*'. The module, class, and method
                        will respectively match the module name, test class
                        name and test method name. Example: --test-tags
                        :TestClass.test_func,/test_module,external Filtering
                        and executing the tests happens twice: right after
                        each module installation/update and at the end of the
                        modules loading. At each stage tests are filtered by
                        --test-tags specs and additionally by dynamic specs
                        'at_install' and 'post_install' correspondingly.
    --screencasts=DIR   Screencasts will go in DIR/{db_name}/screencasts.
    --screenshots=DIR   Screenshots will go in DIR/{db_name}/screenshots.
                        Defaults to /tmp/odoo_tests.

  Logging Configuration:
    --logfile=LOGFILE   file where the server log will be stored
    --syslog            Send the log to the syslog server
    --log-handler=PREFIX:LEVEL
                        setup a handler at LEVEL for a given PREFIX. An empty
                        PREFIX indicates the root logger. This option can be
                        repeated. Example: "odoo.orm:DEBUG" or
                        "werkzeug:CRITICAL" (default: ":INFO")
    --log-web           shortcut for --log-handler=odoo.http:DEBUG
    --log-sql           shortcut for --log-handler=odoo.sql_db:DEBUG
    --log-db=LOG_DB     Logging database
    --log-db-level=LOG_DB_LEVEL
                        Logging database level
    --log-level=LOG_LEVEL
                        specify the level of the logging. Accepted values:
                        ['info', 'debug_rpc', 'warn', 'test', 'critical',
                        'runbot', 'debug_sql', 'error', 'debug',
                        'debug_rpc_answer', 'notset'].

  SMTP Configuration:
    --email-from=EMAIL_FROM
                        specify the SMTP email address for sending email
    --from-filter=FROM_FILTER
                        specify for which email address the SMTP configuration
                        can be used
    --smtp=SMTP_SERVER  specify the SMTP server for sending email
    --smtp-port=SMTP_PORT
                        specify the SMTP port
    --smtp-ssl          if passed, SMTP connections will be encrypted with SSL
                        (STARTTLS)
    --smtp-user=SMTP_USER
                        specify the SMTP username for sending email
    --smtp-password=SMTP_PASSWORD
                        specify the SMTP password for sending email
    --smtp-ssl-certificate-filename=SMTP_SSL_CERTIFICATE_FILENAME
                        specify the SSL certificate used for authentication
    --smtp-ssl-private-key-filename=SMTP_SSL_PRIVATE_KEY_FILENAME
                        specify the SSL private key used for authentication

  Database related options:
    -d DB_NAME, --database=DB_NAME
                        specify the database name
    -r DB_USER, --db_user=DB_USER
                        specify the database user name
    -w DB_PASSWORD, --db_password=DB_PASSWORD
                        specify the database password
    --pg_path=PG_PATH   specify the pg executable path
    --db_host=DB_HOST   specify the database host
    --db_port=DB_PORT   specify the database port
    --db_sslmode=DB_SSLMODE
                        specify the database ssl connection mode (see
                        PostgreSQL documentation)
    --db_maxconn=DB_MAXCONN
                        specify the maximum number of physical connections to
                        PostgreSQL
    --db-template=DB_TEMPLATE
                        specify a custom database template to create a new
                        database

  Internationalisation options:
    Use these options to translate Odoo to another language. See i18n
    section of the user manual. Option '-d' is mandatory. Option '-l' is
    mandatory in case of importation

    --load-language=LOAD_LANGUAGE
                        specifies the languages for the translations you want
                        to be loaded
    -l LANGUAGE, --language=LANGUAGE
                        specify the language of the translation file. Use it
                        with --i18n-export or --i18n-import
    --i18n-export=TRANSLATE_OUT
                        export all sentences to be translated to a CSV file, a
                        PO file or a TGZ archive and exit
    --i18n-import=TRANSLATE_IN
                        import a CSV or a PO file with translations and exit.
                        The '-l' option is required.
    --i18n-overwrite    overwrites existing translation terms on updating a
                        module or importing a CSV or a PO file.
    --modules=TRANSLATE_MODULES
                        specify modules to export. Use in combination with
                        --i18n-export

  Security-related options:
    --no-database-list  Disable the ability to obtain or view the list of
                        databases. Also disable access to the database manager
                        and selector, so be sure to set a proper --database
                        parameter first

  Advanced options:
    --dev=DEV_MODE      Enable developer mode. Param: List of options
                        separated by comma. Options : all, reload, qweb, xml
    --shell-interface=SHELL_INTERFACE
                        Specify a preferred REPL to use in shell mode.
                        Supported REPLs are: [ipython|ptpython|bpython|python]
    --stop-after-init   stop the server after its initialization
    --osv-memory-count-limit=OSV_MEMORY_COUNT_LIMIT
                        Force a limit on the maximum number of records kept in
                        the virtual osv_memory tables. By default there is no
                        limit.
    --transient-age-limit=TRANSIENT_AGE_LIMIT
                        Time limit (decimal value in hours) records created
                        with a TransientModel (mostly wizard) are kept in the
                        database. Default to 1 hour.
    --osv-memory-age-limit=OSV_MEMORY_AGE_LIMIT
                        Deprecated alias to the transient-age-limit option
    --max-cron-threads=MAX_CRON_THREADS
                        Maximum number of threads processing concurrently cron
                        jobs (default 2).
    --unaccent          Try to enable the unaccent extension when creating new
                        databases.
    --geoip-db=GEOIP_DATABASE
                        Absolute path to the GeoIP database file.

  Multiprocessing options:
    --workers=WORKERS   Specify the number of workers, 0 disable prefork mode.
    --limit-memory-soft=LIMIT_MEMORY_SOFT
                        Maximum allowed virtual memory per worker (in bytes),
                        when reached the worker be reset after the current
                        request (default 2048MiB).
    --limit-memory-hard=LIMIT_MEMORY_HARD
                        Maximum allowed virtual memory per worker (in bytes),
                        when reached, any memory allocation will fail (default
                        2560MiB).
    --limit-time-cpu=LIMIT_TIME_CPU
                        Maximum allowed CPU time per request (default 60).
    --limit-time-real=LIMIT_TIME_REAL
                        Maximum allowed Real time per request (default 120).
    --limit-time-real-cron=LIMIT_TIME_REAL_CRON
                        Maximum allowed Real time per cron job. (default:
                        --limit-time-real). Set to 0 for no limit.
    --limit-request=LIMIT_REQUEST
                        Maximum number of request to be processed per worker
                        (default 65536).








Comentarios

Entradas populares de este blog

4. Desarrollando con Odoo (2). Introducción a modulos, vistas, modelos .. Añadir dependencias externas de Python a Odoo

8. Desarrollando con Odoo (6). Herencia de clase en modelos. Herencia de vistas. Operaciones numeradas en Odoo ??