0%

Python - 配置iPython直接在命令行调试Odoo(openerp)代码

0. 先看效果

ipython_oe_run.png

1. 安装ipython

1
pip install ipython

2. 创建ipython配置文件

1
ipython profile create apple

2.1 *列出所有配置文件

1
ipython profile list

2.2 *查看配置文件位置

1
ipython profile locate apple

3. 创建预加载OE配置文件

1
vim ~/.ipython/profile_apple/startup/00-load-oe.py

内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

#!/usr/bin/python
# coding: utf-8
# author: richard
import os
import sys
import configparser


OE_CONF_PTH = '/path/to/app-server-local.conf'


def abs_path(path):
if path.startswith('~'):
return os.path.expanduser(path)
return path


if __name__ == '__main__':
# 加载OE配置文件
conf = configparser.ConfigParser()
conf.read(abs_path(OE_CONF_PTH))
options = dict(conf.items('options'))
db_name = options['db_name']
addons_path = abs_path(options['addons_path'])
proj_path = addons_path.split('/openerp/addons')[0]
openerp_path = addons_path.split('/addons')[0]

# 加入系统路径
sys.path.extend([proj_path, openerp_path])

# OE解析配置
import openerp
openerp.tools.config.parse_config(['-c',abs_path(OE_CONF_PTH)])

# 生成数据库cursor
uid = 1
db_conn = openerp.sql_db.db_connect(db_name)
cr = db_conn.cursor()

# 若要启用连接池,需将代码中所有import改为从openerp引入
# 如 from osv import fields 需改为 from openerp.osv import fields
pool = openerp.pooler.get_pool(db_name)

# 其他预导入的包和方法
import redis
import json
import datetime
from openerp.tools import gen_signature

redis_pool = openerp.redis_pool.redis_pool
redis_ins = redis.Redis(connection_pool=redis_pool)

4. 启动ipython

1
ipython --profile=apple

5. 执行效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Python 3.7.3 (default, Mar 27 2019, 16:54:48)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.34.0 -- An enhanced Interactive Python. Type '?' for help.

IPython profile: apple

In [1]: cr.execute("""select id from res_users where login=%(login)s limit 1""", {'login': 'admin'})

In [2]: cr.dictfetchone()
Out[2]: {'id': 1}

In [3]: user_ids = pool.get('res.users').search(cr, uid, [('login', '=', 'admin')])

In [4]: user_ids
Out[4]: [1]