ir_config_parameter.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. """
  4. Store database-specific configuration parameters
  5. """
  6. import uuid
  7. import logging
  8. from odoo import api, fields, models, _
  9. from odoo.exceptions import ValidationError
  10. from odoo.tools import config, ormcache, mute_logger
  11. _logger = logging.getLogger(__name__)
  12. """
  13. A dictionary holding some configuration parameters to be initialized when the database is created.
  14. """
  15. _default_parameters = {
  16. "database.secret": lambda: str(uuid.uuid4()),
  17. "database.uuid": lambda: str(uuid.uuid1()),
  18. "database.create_date": fields.Datetime.now,
  19. "web.base.url": lambda: "http://localhost:%s" % config.get('http_port'),
  20. "base.login_cooldown_after": lambda: 10,
  21. "base.login_cooldown_duration": lambda: 60,
  22. }
  23. class IrConfigParameter(models.Model):
  24. """Per-database storage of configuration key-value pairs."""
  25. _name = 'ir.config_parameter'
  26. _description = 'System Parameter'
  27. _rec_name = 'key'
  28. _order = 'key'
  29. key = fields.Char(required=True)
  30. value = fields.Text(required=True)
  31. _sql_constraints = [
  32. ('key_uniq', 'unique (key)', 'Key must be unique.')
  33. ]
  34. @mute_logger('odoo.addons.base.models.ir_config_parameter')
  35. def init(self, force=False):
  36. """
  37. Initializes the parameters listed in _default_parameters.
  38. It overrides existing parameters if force is ``True``.
  39. """
  40. # avoid prefetching during module installation, as the res_users table
  41. # may not have all prescribed columns
  42. self = self.with_context(prefetch_fields=False)
  43. for key, func in _default_parameters.items():
  44. # force=True skips search and always performs the 'if' body (because ids=False)
  45. params = self.sudo().search([('key', '=', key)])
  46. if force or not params:
  47. params.set_param(key, func())
  48. @api.model
  49. def get_param(self, key, default=False):
  50. """Retrieve the value for a given key.
  51. :param string key: The key of the parameter value to retrieve.
  52. :param string default: default value if parameter is missing.
  53. :return: The value of the parameter, or ``default`` if it does not exist.
  54. :rtype: string
  55. """
  56. self.check_access_rights('read')
  57. return self._get_param(key) or default
  58. @api.model
  59. @ormcache('key')
  60. def _get_param(self, key):
  61. # we bypass the ORM because get_param() is used in some field's depends,
  62. # and must therefore work even when the ORM is not ready to work
  63. self.flush_model(['key', 'value'])
  64. self.env.cr.execute("SELECT value FROM ir_config_parameter WHERE key = %s", [key])
  65. result = self.env.cr.fetchone()
  66. return result and result[0]
  67. @api.model
  68. def set_param(self, key, value):
  69. """Sets the value of a parameter.
  70. :param string key: The key of the parameter value to set.
  71. :param string value: The value to set.
  72. :return: the previous value of the parameter or False if it did
  73. not exist.
  74. :rtype: string
  75. """
  76. param = self.search([('key', '=', key)])
  77. if param:
  78. old = param.value
  79. if value is not False and value is not None:
  80. if str(value) != old:
  81. param.write({'value': value})
  82. else:
  83. param.unlink()
  84. return old
  85. else:
  86. if value is not False and value is not None:
  87. self.create({'key': key, 'value': value})
  88. return False
  89. @api.model_create_multi
  90. def create(self, vals_list):
  91. self.clear_caches()
  92. return super(IrConfigParameter, self).create(vals_list)
  93. def write(self, vals):
  94. if 'key' in vals:
  95. illegal = _default_parameters.keys() & self.mapped('key')
  96. if illegal:
  97. raise ValidationError(_("You cannot rename config parameters with keys %s", ', '.join(illegal)))
  98. self.clear_caches()
  99. return super(IrConfigParameter, self).write(vals)
  100. def unlink(self):
  101. self.clear_caches()
  102. return super(IrConfigParameter, self).unlink()
  103. @api.ondelete(at_uninstall=False)
  104. def unlink_default_parameters(self):
  105. for record in self.filtered(lambda p: p.key in _default_parameters.keys()):
  106. raise ValidationError(_("You cannot delete the %s record.", record.key))