odoo17核心概念——env

2023-12-24 23:01
文章标签 概念 核心 env odoo17

本文主要是介绍odoo17核心概念——env,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

env在odoo中是一个非常重要的概念,它是一个全局变量,保存了odoo运行环境的重要信息,env分为前端和后端

一、环境(env)

1、前端的env

在web\static\src\env.js中定义,包含两个重要的对象:

  • 全局数据总线bus, 可以在不同的组件之间进行通信
  • 所有的服务services

这个文件非常重要,它定义了两个函数

makeEnv: 初始化env对象。

export function makeEnv() {return {bus: new EventBus(),services: {},debug: odoo.debug,get isSmall() {throw new Error("UI service not initialized!");},};
}

startServices: 启动所有的Service, 这个函数的实现非常巧妙,因为它要在不考虑服务加载顺序的前提下解决服务之间的依赖问题。 其中细节,值得一读。

不过这里只有这两个函数的定义,并没有执行这两个函数, 真正执行这两个函数的位置在 start.js中

const env = makeEnv();
await startServices(env);

服务启动完后, 会放入env的services对象中。 注意其中放的不是服务对象本身,而是start函数的返回值。

2、 后端的env

后端的env在odoo\api.py中定义

"""The Odoo API module defines Odoo Environments and method decorators... todo:: Document this module
"""__all__ = ['Environment','Meta','model','constrains', 'depends', 'onchange', 'returns','call_kw',
]

文件的注释中说明了两点:
1、这个文件定义了odoo环境和方法装饰器
2、todo: 要为这个模块写文档(啥时候写?)
默认导出的对象,odoo后端最重要的一些对象
‘Environment’,
‘Meta’,
‘model’,
‘constrains’, ‘depends’, ‘onchange’, ‘returns’,
‘call_kw’,

from collections.abc import Mappingclass Environment(Mapping):""" The environment stores various contextual data used by the ORM:- :attr:`cr`: the current database cursor (for database queries);- :attr:`uid`: the current user id (for access rights checks);- :attr:`context`: the current context dictionary (arbitrary metadata);- :attr:`su`: whether in superuser mode.It provides access to the registry by implementing a mapping from modelnames to models. It also holds a cache for records, and a datastructure to manage recomputations."""def reset(self):""" Reset the transaction, see :meth:`Transaction.reset`. """self.transaction.reset()def __new__(cls, cr, uid, context, su=False):if uid == SUPERUSER_ID:su = Trueassert context is not Noneargs = (cr, uid, context, su)# determine transaction objecttransaction = cr.transactionif transaction is None:transaction = cr.transaction = Transaction(Registry(cr.dbname))# if env already exists, return itfor env in transaction.envs:if env.args == args:return env# otherwise create environment, and add it in the setself = object.__new__(cls)args = (cr, uid, frozendict(context), su)self.cr, self.uid, self.context, self.su = self.args = argsself.transaction = self.all = transactionself.registry = transaction.registryself.cache = transaction.cacheself._cache_key = {}                    # memo {field: cache_key}self._protected = transaction.protectedtransaction.envs.add(self)return self

env对象存储了不同类型的上下文数据被ORM使用,
- :attr:cr: the current database cursor (for database queries);
- :attr:uid: the current user id (for access rights checks);
- :attr:context: the current context dictionary (arbitrary metadata);
- :attr:su: whether in superuser mode.

env继承自 collection 的Mapping

在文件的末尾有两句import有点意思

# keep those imports here in order to handle cyclic dependencies correctly
from odoo import SUPERUSER_ID
from odoo.modules.registry import Registry

之所以放在文件末尾,是为了正确的处理循环依赖。 姑且先不管的原理是啥了,不过这里引入了一个重要的对象 Regisitry ——后端的注册表

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."""_lock = threading.RLock()_saved_lock = None@lazy_classpropertydef registries(cls):""" A mapping from database names to registries. """size = config.get('registry_lru_size', None)if not size:# Size the LRU depending of the memory limitsif os.name != 'posix':# cannot specify the memory limit soft on windows...size = 42else:# A registry takes 10MB of memory on average, so we reserve# 10Mb (registry) + 5Mb (working memory) per registryavgsz = 15 * 1024 * 1024size = int(config['limit_memory_soft'] / avgsz)return LRU(size)def __new__(cls, db_name):""" Return the registry for the given database name."""with cls._lock:try:return cls.registries[db_name]except KeyError:return cls.new(db_name)finally:# set db tracker - cleaned up at the WSGI dispatching phase in# odoo.http.rootthreading.current_thread().dbname = db_name

这里不想写的过于深入,先摸清系统的大概框架,在需要的时候再去扣细节,这才是学习的正确方法 。

这篇关于odoo17核心概念——env的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/533413

相关文章

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

在Node.js中使用.env文件管理环境变量的全过程

《在Node.js中使用.env文件管理环境变量的全过程》Node.js应用程序通常依赖于环境变量来管理敏感信息或配置设置,.env文件已经成为一种流行的本地管理这些变量的方法,本文将探讨.env文件... 目录引言为什么使php用 .env 文件 ?如何在 Node.js 中使用 .env 文件最佳实践引

Java Instrumentation从概念到基本用法详解

《JavaInstrumentation从概念到基本用法详解》JavaInstrumentation是java.lang.instrument包提供的API,允许开发者在类被JVM加载时对其进行修改... 目录一、什么是 Java Instrumentation主要用途二、核心概念1. Java Agent

Python异常处理之避免try-except滥用的3个核心原则

《Python异常处理之避免try-except滥用的3个核心原则》在Python开发中,异常处理是保证程序健壮性的关键机制,本文结合真实案例与Python核心机制,提炼出避免异常滥用的三大原则,有需... 目录一、精准打击:只捕获可预见的异常类型1.1 通用异常捕获的陷阱1.2 精准捕获的实践方案1.3

深入浅出Java中的Happens-Before核心规则

《深入浅出Java中的Happens-Before核心规则》本文解析Java内存模型中的Happens-Before原则,解释其定义、核心规则及实际应用,帮助理解多线程可见性与有序性问题,掌握并发编程... 目录前言一、Happens-Before是什么?为什么需要它?1.1 从一个问题说起1.2 Haht

Kotlin 协程之Channel的概念和基本使用详解

《Kotlin协程之Channel的概念和基本使用详解》文章介绍协程在复杂场景中使用Channel进行数据传递与控制,涵盖创建参数、缓冲策略、操作方式及异常处理,适用于持续数据流、多协程协作等,需注... 目录前言launch / async 适合的场景Channel 的概念和基本使用概念Channel 的

redis-sentinel基础概念及部署流程

《redis-sentinel基础概念及部署流程》RedisSentinel是Redis的高可用解决方案,通过监控主从节点、自动故障转移、通知机制及配置提供,实现集群故障恢复与服务持续可用,核心组件包... 目录一. 引言二. 核心功能三. 核心组件四. 故障转移流程五. 服务部署六. sentinel部署

Python进阶之列表推导式的10个核心技巧

《Python进阶之列表推导式的10个核心技巧》在Python编程中,列表推导式(ListComprehension)是提升代码效率的瑞士军刀,本文将通过真实场景案例,揭示列表推导式的进阶用法,希望对... 目录一、基础语法重构:理解推导式的底层逻辑二、嵌套循环:破解多维数据处理难题三、条件表达式:实现分支

深度解析Python yfinance的核心功能和高级用法

《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?

一文带你迅速搞懂路由器/交换机/光猫三者概念区别

《一文带你迅速搞懂路由器/交换机/光猫三者概念区别》讨论网络设备时,常提及路由器、交换机及光猫等词汇,日常生活、工作中,这些设备至关重要,居家上网、企业内部沟通乃至互联网冲浪皆无法脱离其影响力,本文将... 当谈论网络设备时,我们常常会听到路由器、交换机和光猫这几个名词。它们是构建现代网络基础设施的关键组成