odoo 创建初始数据库 切换当前数据库

from odoo import models, fields, api, sql_db, tools
from contextlib import closing
from odoo.exceptions import ValidationError
from odoo.service.db import _initialize_db


def change_current_database(to_database_name):
    """
    切换当前数据库
    :param to_database_name: 目标数据库
    :return:
    """
    tools.config['db_name'] = to_database_name


def create_empty_database(database_name):
    """
    根据database_name 创建空数据库, 参考函数odoo.service.db._create_empty_database
    :param database_name: 创建空数据库名
    :return:
    """
    db = sql_db.db_connect('postgres')
    with closing(db.cursor()) as cr:
        chosen_template = tools.config['db_template']
        cr.execute("SELECT datname FROM pg_database WHERE datname = %s",
                   (database_name,), log_exceptions=False)
        if cr.fetchall():
            return False
        else:
            cr.autocommit(True)  # avoid transaction block
            collate = "LC_COLLATE 'C'" if chosen_template == 'template0' else ""
            cr.execute(
                """CREATE DATABASE "%s" ENCODING 'unicode' %s TEMPLATE "%s" """ %
                (database_name, collate, chosen_template)
            )
            return True


def create_odoo_database(database_name):
    """
    创建有odoo初始数据的数据库
    :param database_name:
    :return:
    """
    if create_empty_database(database_name):
        _initialize_db(
            id,
            db_name=database_name,
            demo=False,
            lang=None,
            user_password='admin',
            login='admin',
            country_code=None,
            phone=None
        )
    else:
        return False

posted @ 2019-10-12 10:55  twfb  阅读(1880)  评论(0编辑  收藏  举报