当前位置: 首页>>代码示例>>Python>>正文


Python odoo.SUPERUSER_ID属性代码示例

本文整理汇总了Python中odoo.SUPERUSER_ID属性的典型用法代码示例。如果您正苦于以下问题:Python odoo.SUPERUSER_ID属性的具体用法?Python odoo.SUPERUSER_ID怎么用?Python odoo.SUPERUSER_ID使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在odoo的用法示例。


在下文中一共展示了odoo.SUPERUSER_ID属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_last_post_for_model

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def get_last_post_for_model(cr, uid, ids, model_pool):
    """
    Given a set of ids and a model pool, return a dict of each object ids with
    their latest message date as a value.
    To be called in post-migration scripts

    :param cr: database cursor
    :param uid: user id, assumed to be openerp.SUPERUSER_ID
    :param ids: ids of the model in question to retrieve ids
    :param model_pool: orm model pool, assumed to be from pool.get()
    :return: a dict with ids as keys and with dates as values
    """
    if type(ids) is not list:
        ids = [ids]
    res = {}
    for obj in model_pool.browse(cr, uid, ids):
        message_ids = obj.message_ids
        if message_ids:
            res[obj.id] = sorted(
                message_ids, key=lambda x: x.date, reverse=True)[0].date
        else:
            res[obj.id] = False
    return res 
开发者ID:OCA,项目名称:openupgradelib,代码行数:25,代码来源:openupgrade_80.py

示例2: add_book_hook

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def add_book_hook(cr, registry):
    env = api.Environment(cr, SUPERUSER_ID, {})
    book_data1 = {'name': 'Book 1', 'date_release': fields.Date.today()}
    book_data2 = {'name': 'Book 2', 'date_release': fields.Date.today()}
    env['library.book'].create([book_data1, book_data2]) 
开发者ID:PacktPublishing,项目名称:Odoo-12-Development-Cookbook-Third-Edition,代码行数:7,代码来源:__init__.py

示例3: OdooEnvironment

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def OdooEnvironment(database, rollback=False, **kwargs):
    with Environment.manage():
        registry = odoo.registry(database)
        try:
            with registry.cursor() as cr:
                uid = odoo.SUPERUSER_ID
                try:
                    ctx = Environment(cr, uid, {})["res.users"].context_get()
                except Exception as e:
                    ctx = {"lang": "en_US"}
                    # this happens, for instance, when there are new
                    # fields declared on res_partner which are not yet
                    # in the database (before -u)
                    _logger.warning(
                        "Could not obtain a user context, continuing "
                        "anyway with a default context. Error was: %s",
                        e,
                    )
                env = Environment(cr, uid, ctx)
                cr.rollback()
                yield env
                if rollback:
                    cr.rollback()
                else:
                    cr.commit()
        finally:
            if odoo.tools.parse_version(
                odoo.release.version
            ) < odoo.tools.parse_version("10.0"):
                odoo.modules.registry.RegistryManager.delete(database)
            else:
                odoo.modules.registry.Registry.delete(database)
            odoo.sql_db.close_db(database) 
开发者ID:acsone,项目名称:click-odoo,代码行数:35,代码来源:env.py

示例4: render

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def render(self):
        """ Renders the Response's template, returns the result
        """
        env = request.env(user=self.uid or request.uid or odoo.SUPERUSER_ID)
        self.qcontext['request'] = request
        return env["ir.ui.view"].render_template(self.template, self.qcontext) 
开发者ID:ocubexo,项目名称:odoo-dingtalk-connector,代码行数:8,代码来源:http.py

示例5: _get_translation

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def _get_translation(self, source):
        res = source
        cr = None
        is_new_cr = False
        try:
            frame = inspect.currentframe()
            if frame is None:
                return source
            frame = frame.f_back
            if not frame:
                return source
            frame = frame.f_back
            if not frame:
                return source
            lang = self._get_lang(frame)
            if lang:
                cr, is_new_cr = self._get_cr(frame)
                if cr:
                    # Try to use ir.translation to benefit from global cache if possible
                    env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, {})
                    res = env['ir.translation']._get_source(None, ('code',), lang, source)
                else:
                    _logger.debug('no context cursor detected, skipping translation for "%r"', source)
            else:
                _logger.debug('no translation language detected, skipping translation for "%r" ', source)
        except Exception:
            _logger.debug('translation went wrong for "%r", skipped', source)
                # if so, double-check the root/base translations filenames
        finally:
            if cr and is_new_cr:
                cr.close()
        return res 
开发者ID:guohuadeng,项目名称:odoo13-x64,代码行数:34,代码来源:translate.py

示例6: load_language

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def load_language(cr, lang):
    """ Loads a translation terms for a language.
    Used mainly to automate language loading at db initialization.

    :param lang: language ISO code with optional _underscore_ and l10n flavor (ex: 'fr', 'fr_BE', but not 'fr-BE')
    :type lang: str
    """
    env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, {})
    installer = env['base.language.install'].create({'lang': lang})
    installer.lang_install() 
开发者ID:guohuadeng,项目名称:odoo13-x64,代码行数:12,代码来源:translate.py

示例7: _build_odoo_env

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def _build_odoo_env(self, odoo_args):
        odoo.tools.config.parse_config(odoo_args)
        dbname = odoo.tools.config['db_name']
        odoo.tools.config['workers'] = 0
        odoo.tools.config['xmlrpc'] = False
        if not dbname:
            argparse.ArgumentParser().error(
                "please provide a database name though Odoo options (either "
                "-d or an Odoo configuration file)"
            )
        logging.getLogger(odoo_logger).setLevel(logging.ERROR)
        odoo.service.server.start(preload=[], stop=True)

        # odoo.service.server.start() modifies the SIGINT signal by its own
        # one which in fact prevents us to stop anthem with Ctrl-c.
        # Restore the default one.
        signal.signal(signal.SIGINT, signal.default_int_handler)
        odoo_version = odoo.release.version_info[0]
        # On saas versions this will be "saas-XX" where XX is the odoo version
        if not isinstance(odoo_version, int):
            odoo_version = int(
                odoo_version.lstrip(string.ascii_letters + '-~')
            )
        if odoo_version > 9:
            registry = odoo.modules.registry.Registry(dbname)
        else:
            registry = odoo.modules.registry.RegistryManager.get(dbname)
        cr = registry.cursor()
        uid = odoo.SUPERUSER_ID
        Environment.reset()
        context = Environment(cr, uid, {})['res.users'].context_get()
        return Environment(cr, uid, context) 
开发者ID:camptocamp,项目名称:anthem,代码行数:34,代码来源:cli.py

示例8: update_aliases

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def update_aliases(
        cr, registry, model_name, set_parent_thread_id,
        alias_defaults=None, defaults_id_key=False):
    """
    Update a model's aliases according to how they are configured
    in the model's create() method.

    :param model_name: The name of the model whose aliases are to be updated. \
    The model_id is also set as the aliases' alias_parent_model_id.
    :param set_parent_thread_id': When set, set the ids of the resources as \
    their alias' alias_parent_thread_id
    :param alias_defaults: Static dictionary, recorded as a string on each \
    alias
    :param defaults_id_key: When defined, add this key to each alias' \
    defaults dictionary with the resource id as its value.
    """
    model_id = registry['ir.model'].search(
        cr, SUPERUSER_ID, [('model', '=', model_name)])[0]
    vals = {'alias_parent_model_id': model_id}
    if defaults_id_key and alias_defaults is None:
        alias_defaults = {}
    res_ids = registry[model_name].search(
        cr, SUPERUSER_ID, [], context={'active_test': False})
    for res in registry[model_name].browse(
            cr, SUPERUSER_ID, res_ids):
        if set_parent_thread_id:
            vals['alias_parent_thread_id'] = res.id
        if defaults_id_key:
            alias_defaults[defaults_id_key] = res.id
        if alias_defaults is not None:
            vals['alias_defaults'] = str(alias_defaults)
        res.alias_id.write(vals) 
开发者ID:OCA,项目名称:openupgradelib,代码行数:34,代码来源:openupgrade_80.py

示例9: signin_3rd

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def signin_3rd(self, **kw):
        state = json.loads(kw['state'])
        dbname = state['d']
        provider = state['p']
        context = state.get('c', {})
        registry = registry_get(dbname)
        with registry.cursor() as cr:
            try:
                env = api.Environment(cr, SUPERUSER_ID, context)
                credentials = env['res.users'].sudo().auth_oauth_third(provider, kw)
                cr.commit()
                action = state.get('a')
                menu = state.get('m')
                redirect = werkzeug.url_unquote_plus(state['r']) if state.get('r') else False
                url = '/web'
                if redirect:
                    url = redirect
                elif action:
                    url = '/web#action=%s' % action
                elif menu:
                    url = '/web#menu_id=%s' % menu
                if credentials[0]==-1:
                    from .controllers import gen_id
                    credentials[1]['oauth_provider_id'] = provider
                    qr_id = gen_id(credentials[1])
                    redirect = base64.urlsafe_b64encode(redirect.encode('utf-8')).decode('utf-8')
                    url = '/corp/bind?qr_id=%s&redirect=%s'%(qr_id, redirect)
                else:
                    return login_and_redirect(*credentials, redirect_url=url)
            except AttributeError:
                import traceback;traceback.print_exc()
                # auth_signup is not installed
                _logger.error("auth_signup not installed on database %s: oauth sign up cancelled." % (dbname,))
                url = "/web/login?oauth_error=1"
            except AccessDenied:
                import traceback;traceback.print_exc()
                # oauth credentials not valid, user could be on a temporary session
                _logger.info('OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies')
                url = "/web/login?oauth_error=3"
                redirect = werkzeug.utils.redirect(url, 303)
                redirect.autocorrect_location_header = False
                return redirect
            except Exception as e:
                # signup error
                _logger.exception("OAuth2: %s" % str(e))
                url = "/web/login?oauth_error=2"

        return set_cookie_and_redirect(url) 
开发者ID:JoneXiong,项目名称:weodoo,代码行数:50,代码来源:oauth_signin_3rd.py

示例10: trans_load_data

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def trans_load_data(cr, fileobj, fileformat, lang, lang_name=None, verbose=True, module_name=None, context=None):
    """Populates the ir_translation table."""
    if verbose:
        _logger.info('loading translation file for language %s', lang)

    env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, context or {})
    Lang = env['res.lang']
    Translation = env['ir.translation']

    try:
        if not Lang.search_count([('code', '=', lang)]):
            # lets create the language with locale information
            Lang.load_lang(lang=lang, lang_name=lang_name)

        # now, the serious things: we read the language file
        fileobj.seek(0)
        reader = TranslationFileReader(fileobj, fileformat=fileformat)

        # read the rest of the file
        irt_cursor = Translation._get_import_cursor()

        def process_row(row):
            """Process a single PO (or POT) entry."""
            # dictionary which holds values for this line of the csv file
            # {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,
            #  'src': ..., 'value': ..., 'module':...}
            dic = dict.fromkeys(('type', 'name', 'res_id', 'src', 'value',
                                 'comments', 'imd_model', 'imd_name', 'module'))
            dic['lang'] = lang
            dic.update(row)

            # do not import empty values
            if not env.context.get('create_empty_translation', False) and not dic['value']:
                return

            if dic['type'] == 'code' and module_name:
                dic['module'] = module_name

            irt_cursor.push(dic)

        # First process the entries from the PO file (doing so also fills/removes
        # the entries from the POT file).
        for row in reader:
            process_row(row)

        irt_cursor.finish()
        Translation.clear_caches()
        if verbose:
            _logger.info("translation file loaded successfully")

    except IOError:
        iso_lang = get_iso_codes(lang)
        filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat)
        _logger.exception("couldn't read translation file %s", filename) 
开发者ID:guohuadeng,项目名称:odoo13-x64,代码行数:56,代码来源:translate.py

示例11: open

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def open(self, db=None, with_demo=False):
        """Load the database

        Loading an empty database in Odoo has the side effect of installing
        the ``base`` module. Whether to loading demo data or not has therefore
        to be decided right away.

        :param db: database name. If not specified, the same cascading of
                   defaults as Odoo mainstream will be applied:
                   configuration file, psycopg2/lipq defaults.
        :param with_demo: controls the loading of demo data for all
                          module installations triggered by this call to
                          :meth:`open` and further uses of :meth:`load_modules`
                          on this :class:`Session` instance:

                          * if ``True``, demo data will uniformly be loaded
                          * if ``False``, no demo data will be loaded
                          * if ``None``, demo data will be loaded according to
                            the value of ``without_demo`` in configuration

                          In all cases, the behaviour will stay consistent
                          until the next call of ``open()``, but the
                          implementation does not protect against any race
                          conditions in Odoo internals.
        """
        if db is None:
            db = config['db_name']
        if not db:
            db = ''  # expected value expected by Odoo to start defaulting.

        cnx = odoo.sql_db.db_connect(db)
        cr = cnx.cursor()
        self.is_initialization = not(odoo.modules.db.is_initialized(cr))
        cr.close()

        startup.check_root_user()
        if not os.environ.get('ENABLE_POSTGRES_USER'):
            startup.check_postgres_user()
        odoo.netsvc.init_logger()

        saved_without_demo = config['without_demo']
        if with_demo is None:
            with_demo = config['without_demo']

        config['without_demo'] = not with_demo
        self.with_demo = with_demo

        if version_info[0] <= 10:
            self._registry = Registry.get(
                db, update_module=False)
        else:
            # Form Odoo 11.0: no get method available
            self._registry = Registry(db)
        config['without_demo'] = saved_without_demo
        self.init_cursor()
        self.uid = SUPERUSER_ID
        self.init_environments()
        self.context = self.env['res.users'].context_get()
        self.env = odoo.api.Environment(self.cr, self.uid, self.context) 
开发者ID:anybox,项目名称:anybox.recipe.odoo,代码行数:61,代码来源:session.py

示例12: add_xmlid

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def add_xmlid(cr, module, xmlid, model, res_id, noupdate=False):
    """
    Adds an entry in ir_model_data. Typically called in the pre script.
    One usage example is when an entry has been add in the XML and there is
    a high probability that the user has already created the entry manually.
    For example, a currency was added in the XML data of the base module
    in OpenERP 6 but the user had already created this missing currency
    by hand in it's 5.0 database. In order to avoid having 2 identical
    currencies (which is in fact blocked by an sql_constraint), you have to
    add the entry in ir_model_data before the upgrade.
    """
    # Check if the XMLID doesn't already exists
    cr.execute(
        "SELECT id FROM ir_model_data WHERE module=%s AND name=%s "
        "AND model=%s",
        (module, xmlid, model))
    already_exists = cr.fetchone()
    if already_exists:
        return False
    else:
        logged_query(
            cr,
            "INSERT INTO ir_model_data (create_uid, create_date, "
            "write_uid, write_date, date_init, date_update, noupdate, "
            "name, module, model, res_id) "
            "VALUES (%s, (now() at time zone 'UTC'), %s, "
            "(now() at time zone 'UTC'), (now() at time zone 'UTC'), "
            "(now() at time zone 'UTC'), %s, %s, %s, %s, %s)", (
                SUPERUSER_ID, SUPERUSER_ID, noupdate,
                xmlid, module, model, res_id))
        return True 
开发者ID:OCA,项目名称:openupgradelib,代码行数:33,代码来源:openupgrade.py

示例13: update_workflow_workitems

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def update_workflow_workitems(cr, pool, ref_spec_actions):
    """Find all the workflow items from the target state to set them to
    the wanted state.

    When a workflow action is removed, from model, the objects whose states
    are in these actions need to be set to another to be able to continue the
    workflow properly.

    Run in pre-migration

    :param ref_spec_actions: list of tuples with couple of workflow.action's
        external ids. The first id is replaced with the second.
    :return: None

    .. versionadded:: 7.0
    """
    workflow_workitems = pool['workflow.workitem']
    ir_model_data_model = pool['ir.model.data']

    for (target_external_id, fallback_external_id) in ref_spec_actions:
        target_activity = ir_model_data_model.get_object(
            cr, SUPERUSER_ID,
            target_external_id.split(".")[0],
            target_external_id.split(".")[1],
        )
        fallback_activity = ir_model_data_model.get_object(
            cr, SUPERUSER_ID,
            fallback_external_id.split(".")[0],
            fallback_external_id.split(".")[1],
        )
        ids = workflow_workitems.search(
            cr, SUPERUSER_ID, [('act_id', '=', target_activity.id)]
        )
        if ids:
            logger.info(
                "Moving %d items in the removed workflow action (%s) to a "
                "fallback action (%s): %s",
                len(ids), target_activity.name, fallback_activity.name, ids
            )
            workflow_workitems.write(
                cr, SUPERUSER_ID, ids, {'act_id': fallback_activity.id}
            ) 
开发者ID:OCA,项目名称:openupgradelib,代码行数:44,代码来源:openupgrade.py

示例14: warn_possible_dataloss

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def warn_possible_dataloss(cr, pool, old_module, fields):
    """
    Use that function in the following case:
    if a field of a model was moved from a 'A' module to a 'B' module.
    ('B' depend on 'A'),
    This function will test if 'B' is installed.
    If not, count the number of different value and possibly warn the user.
    Use orm, so call from the post script.

    :param old_module: name of the old module
    :param fields: list of dictionary with the following keys:
        'table' : name of the table where the field is.
        'field' : name of the field that are moving.
        'new_module' : name of the new module

    .. versionadded:: 7.0
    """
    module_obj = pool.get('ir.module.module')
    for field in fields:
        module_ids = module_obj.search(
            cr, SUPERUSER_ID, [
                ('name', '=', field['new_module']),
                ('state', 'in', ['installed', 'to upgrade', 'to install'])
            ])
        if not module_ids:
            cr.execute(
                "SELECT count(*) FROM (SELECT %s from %s group by %s) "
                "as tmp" % (
                    field['field'], field['table'], field['field']))
            row = cr.fetchone()
            if row[0] == 1:
                # not a problem, that field wasn't used.
                # Just a loss of functionality
                logger.info(
                    "Field '%s' from module '%s' was moved to module "
                    "'%s' which is not installed: "
                    "No dataloss detected, only loss of functionality"
                    % (field['field'], old_module, field['new_module']))
            else:
                # there is data loss after the migration.
                message(
                    cr, old_module, None, None,
                    "Field '%s' was moved to module "
                    "'%s' which is not installed: "
                    "There were %s distinct values in this field.",
                    field['field'], field['new_module'], row[0]) 
开发者ID:OCA,项目名称:openupgradelib,代码行数:48,代码来源:openupgrade.py

示例15: deactivate_workflow_transitions

# 需要导入模块: import odoo [as 别名]
# 或者: from odoo import SUPERUSER_ID [as 别名]
def deactivate_workflow_transitions(cr, model, transitions=None):
    """
    Disable workflow transitions for workflows on a given model.
    This can be necessary for automatic workflow transitions when writing
    to an object via the ORM in the post migration step.
    Returns a dictionary to be used on reactivate_workflow_transitions

    :param model: the model for which workflow transitions should be \
    deactivated
    :param transitions: a list of ('module', 'name') xmlid tuples of \
    transitions to be deactivated. Don't pass this if there's no specific \
    reason to do so, the default is to deactivate all transitions

    .. versionadded:: 7.0
    """
    transition_ids = []
    if transitions:
        data_obj = registry.get(cr.dbname)['ir.model.data']
        for module, name in transitions:
            try:
                transition_ids.append(
                    data_obj.get_object_reference(
                        cr, SUPERUSER_ID, module, name)[1])
            except ValueError:
                continue
    else:
        cr.execute(
            '''select distinct t.id
            from wkf w
            join wkf_activity a on a.wkf_id=w.id
            join wkf_transition t
                on t.act_from=a.id or t.act_to=a.id
            where w.osv=%s''', (model,))
        transition_ids = [i for i, in cr.fetchall()]
    cr.execute(
        'select id, condition from wkf_transition where id in %s',
        (tuple(transition_ids),))
    transition_conditions = dict(cr.fetchall())
    cr.execute(
        "update wkf_transition set condition = 'False' WHERE id in %s",
        (tuple(transition_ids),))
    return transition_conditions 
开发者ID:OCA,项目名称:openupgradelib,代码行数:44,代码来源:openupgrade.py


注:本文中的odoo.SUPERUSER_ID属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。