odoo13源码-003:server.py 转载自https://blog.csdn.net/jason156/article/details/104912446

odoo13源码-003:server.py

jason156 2020-03-17 00:29:31  83  收藏

分类专栏: Odoo源码学习

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:http://blog.csdn.net/jason156/article/details/104912446

收起

 
  1. # -*- coding: utf-8 -*-

  2.  
  3.  
  4. """

  5. # Server类用于启动odoo服务,启动方法为run,而run 执行的是server.py中的 main()方法

  6. """

  7.  
  8. import atexit

  9. import csv # pylint: disable=deprecated-module

  10. import logging

  11. import os

  12. import signal

  13. import sys

  14. import threading

  15. import traceback

  16. import time

  17.  
  18. from psycopg2 import ProgrammingError, errorcodes

  19.  
  20. import odoo

  21.  
  22. from . import Command

  23.  
  24. __author__ = odoo.release.author

  25. __version__ = odoo.release.version

  26.  
  27. # Also use the `odoo` logger for the main script.

  28. _logger = logging.getLogger('odoo')

  29.  
  30. def check_root_user(): #检查linux下的用户名是否是root,如果是就警告

  31. """Warn if the process's user is 'root' (on POSIX system)."""

  32. if os.name == 'posix':

  33. import getpass

  34. if getpass.getuser() == 'root':

  35. sys.stderr.write("Running as user 'root' is a security risk.\n")

  36.  
  37. def check_postgres_user(): #检查pg数据库的用户名是否是postgres

  38. """ Exit if the configured database user is 'postgres'.

  39.  
  40. This function assumes the configuration has been initialized.

  41. """

  42. config = odoo.tools.config

  43. if (config['db_user'] or os.environ.get('PGUSER')) == 'postgres':

  44. sys.stderr.write("Using the database user 'postgres' is a security risk, aborting.")

  45. sys.exit(1)

  46.  
  47. def report_configuration():

  48. """ Log the server version and some configuration values.

  49.  
  50. This function assumes the configuration has been initialized.

  51. """

  52. config = odoo.tools.config

  53. _logger.info("Odoo version %s", __version__)

  54. if os.path.isfile(config.rcfile):

  55. _logger.info("Using configuration file at " + config.rcfile)

  56. _logger.info('addons paths: %s', odoo.addons.__path__)

  57. if config.get('upgrades_paths'):

  58. _logger.info('upgrades path: %s', config['upgrades_paths'])

  59. host = config['db_host'] or os.environ.get('PGHOST', 'default')

  60. port = config['db_port'] or os.environ.get('PGPORT', 'default')

  61. user = config['db_user'] or os.environ.get('PGUSER', 'default')

  62. _logger.info('database: %s@%s:%s', user, host, port)

  63.  
  64. # 移除pid文件

  65. def rm_pid_file(main_pid):

  66. config = odoo.tools.config

  67. if config['pidfile'] and main_pid == os.getpid():

  68. try:

  69. os.unlink(config['pidfile'])

  70. except OSError:

  71. pass

  72.  
  73. # 创建新的pid文件

  74. def setup_pid_file():

  75. """ Create a file with the process id written in it.

  76.  
  77. This function assumes the configuration has been initialized.

  78. """

  79. config = odoo.tools.config

  80. if not odoo.evented and config['pidfile']:

  81. pid = os.getpid()

  82. with open(config['pidfile'], 'w') as fd:

  83. fd.write(str(pid))

  84. atexit.register(rm_pid_file, pid)

  85.  
  86. # 导出翻译

  87. def export_translation():

  88. config = odoo.tools.config

  89. dbname = config['db_name']

  90.  
  91. if config["language"]:

  92. msg = "language %s" % (config["language"],)

  93. else:

  94. msg = "new language"

  95. _logger.info('writing translation file for %s to %s', msg,

  96. config["translate_out"])

  97.  
  98. fileformat = os.path.splitext(config["translate_out"])[-1][1:].lower()

  99.  
  100. with open(config["translate_out"], "wb") as buf:

  101. registry = odoo.modules.registry.Registry.new(dbname) # 每个数据库注册为一个Registry.

  102. # 模块加载外层就是封装一个Registry(Mapping)对象:实际是一个字典,它包含对应的db,model等映射关系,一个DB对应一个Registry。

  103. # 后续的操作都会围绕这个Registry进行,将相关的数据赋值给相应的属性项。

  104. with odoo.api.Environment.manage():

  105. with registry.cursor() as cr:

  106. odoo.tools.trans_export(config["language"],

  107. config["translate_modules"] or ["all"], buf, fileformat, cr)

  108.  
  109. _logger.info('translation file written successfully')

  110.  
  111.  
  112. # 导入翻译

  113. def import_translation():

  114. config = odoo.tools.config

  115. context = {'overwrite': config["overwrite_existing_translations"]}

  116. dbname = config['db_name']

  117.  
  118. registry = odoo.modules.registry.Registry.new(dbname)

  119. with odoo.api.Environment.manage():

  120. with registry.cursor() as cr:

  121. odoo.tools.trans_load(

  122. cr, config["translate_in"], config["language"], context=context,

  123. )

  124.  
  125. """

  126. 启动检查是否为系统Root用户

  127. 检查是否是pg管理员用户postgres

  128.  
  129. """

  130. def main(args):

  131. check_root_user()

  132. odoo.tools.config.parse_config(args)

  133. check_postgres_user()

  134. report_configuration()

  135.  
  136. config = odoo.tools.config

  137.  
  138. # the default limit for CSV fields in the module is 128KiB, which is not

  139. # quite sufficient to import images to store in attachment. 500MiB is a

  140. # bit overkill, but better safe than sorry I guess

  141. csv.field_size_limit(500 * 1024 * 1024)

  142.  
  143. preload = []

  144. if config['db_name']:

  145. preload = config['db_name'].split(',')

  146. for db_name in preload:

  147. try:

  148. odoo.service.db._create_empty_database(db_name) # 创建空的数据库

  149. config['init']['base'] = True

  150. except ProgrammingError as err:

  151. if err.pgcode == errorcodes.INSUFFICIENT_PRIVILEGE:

  152. # We use an INFO loglevel on purpose in order to avoid

  153. # reporting unnecessary warnings on build environment

  154. # using restricted database access.

  155. _logger.info("Could not determine if database %s exists, "

  156. "skipping auto-creation: %s", db_name, err)

  157. else:

  158. raise err

  159. except odoo.service.db.DatabaseExists:

  160. pass

  161.  
  162. if config["translate_out"]:

  163. export_translation()

  164. sys.exit(0)

  165.  
  166. if config["translate_in"]:

  167. import_translation()

  168. sys.exit(0)

  169.  
  170. # This needs to be done now to ensure the use of the multiprocessing

  171. # signaling mecanism for registries loaded with -d

  172. if config['workers']:

  173. odoo.multi_process = True

  174.  
  175. stop = config["stop_after_init"]

  176.  
  177. # 启动odoo的http服务,执行service目录下的server.py中的start()方法

  178. setup_pid_file()

  179. rc = odoo.service.server.start(preload=preload, stop=stop)

  180. sys.exit(rc)

  181.  
  182. class Server(Command):

  183. """Start the odoo server (default command)"""

  184. def run(self, args): #被command 调用, 然后又调用本单元的main方法

  185. main(args)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值