odoo 数据库连接层

这篇博客探讨了Odoo的数据库连接层,重点介绍了Cursor、Environment、Registry、Connection和ConnectionPool等关键类的实现及作用。内容涵盖连接过程、Environment中的cr实现以及如何通过env.cr管理ConnectionPool连接池,解释了Odoo如何通过连接池维持数据库的长连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、概述

   odoo的数据库连接层功能是连接odoo code与数据库,在odoo.sql_db模块中实现,区别于ORM。

二、涉及的类

   涉及的类主要有:①Cursor,cr变量所指向的对象②Environment,可以访问访问cr、uid、context、注册类、管理记录集缓存;③Registry,能够获取到注册model,cursor()方法能返回新的游标;④Connection⑤ConnectionPool,直接实现与数据库的连接。

三、cr的实现过程

   3.1 第一步,请求处理

#  截取部分代码
Class Root(object):
    def dispatch(self, environ, start_response):
        #  pass
        with request:
            db = request.session.db
            if db:
                try:
                    # 调用odoo.registry()
                    odoo.registry(db).check_signaling()
                    with odoo.tools.mute_logger('odoo.sql_db'):
                        ir_http = request.registry['ir.http']
                except (AttributeError, psycopg2.OperationalError, psycopg2.ProgrammingError):
        #  pass

   3.2 第二步,使用db_name创建并初始化Registry实例

#  odoo/__init__.py/def registry()
def registry(database_name=None):
    """
    Return the model registry for the given database, or the database mentioned
    on the current thread. If the registry does not exist yet, it is created on
    the fly.
    """
    if database_name is None:
        import threading
        database_name = threading.currentThread().dbname
        #  创建Registry对象
    return modules.registry.Registry(database_name)

#  odoo/modules/registry.py
#  创建Registry对象具体实现
class Registry(Mapping):
    """ Model registry for a particular database.

    The registry is essentially a mapping between model names and model classes.
    There is one registry instance per database.
    model名字与类之间的映射

    """
    #  返回Registry对象
    def __new__(cls, db_name):
        """ Return the registry for the given database name."""
        with cls._lock:
            try:
                return cls.registries[db_name]
            except KeyError:
                #  返回Registry对象的实现方法调用
                return cls.new(db_name)
            finally:
                # set db tracker - cleaned up at the WSGI dispatching phase in
                # odoo.service.wsgi_server.application
                threading.current_thread().dbname = db_name
    
    #  返回Registry对象
    @classmethod
    def new(cls, db_name, force_demo=False, status=None, update_module=False):
        """ Create and return a new registry for the given database name. """
        with cls._lock:
            with odoo.api.Environment.manage():
                registry = object.__new__(cls)
                #  调用初始化方法
                registry.init(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值