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


Python i18n._函数代码示例

本文整理汇总了Python中rdiffweb.i18n._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: _handle_set_profile_info

    def _handle_set_profile_info(self, **kwargs):
        """
        Called when changing user profile.
        """
        # Check data.
        if 'email' not in kwargs:
            raise ValueError(_("email is undefined"))

        # Check if email update is supported
        if not self.app.userdb.supports('set_email'):
            return {'error': _("Email update is not supported.")}

        # Parse the email value to extract a valid email. The following method
        # return an empty string if the email is not valid. This RFC also accept
        # local email address without '@'. So we add verification for '@'
        if not PATTERN_EMAIL.match(kwargs['email'].lower()):
            raise ValueError(_("invalid email"))

        # Update the user's email
        if not self.app.currentuser:
            raise RdiffError(_("invalid state"))

        username = self.app.currentuser.username
        email = kwargs['email']
        _logger.info("updating user [%s] email [%s]", username, email)
        self.app.userdb.set_email(username, kwargs['email'])

        return {'success': _("Profile updated successfully.")}
开发者ID:fliphess,项目名称:rdiffweb,代码行数:28,代码来源:__init__.py

示例2: index

    def index(self, path=b'', new_encoding=None):
        """
        Update repository encoding via Ajax.
        """
        self.assertIsInstance(path, bytes)
        self.assertTrue(new_encoding)

        _logger.debug("update repo [%r] settings [%r]", path, new_encoding)

        # Check user permissions
        repo_obj = self.validate_user_path(path)[0]

        # Validate the encoding value
        new_codec = encodings.search_function(new_encoding.lower())
        if not new_codec:
            raise cherrypy.HTTPError(400, _("invalid encoding value"))

        new_encoding = new_codec.name
        if not isinstance(new_encoding, str):
            # Python 2
            new_encoding = new_encoding.decode('ascii')

        # Update the repository encoding
        _logger.info("updating repository [%s] encoding [%s]", repo_obj, new_encoding)
        repo_obj.set_encoding(new_encoding)

        return _("Updated")
开发者ID:ikus060,项目名称:rdiffweb,代码行数:27,代码来源:__init__.py

示例3: check_crendential

        def check_crendential(l, r):
            # Check results
            if len(r) != 1:
                logger.debug("user [%s] not found in LDAP", username)
                return None

            # Bind using the user credentials. Throws an exception in case of
            # error.
            l.simple_bind_s(r[0][0], password)
            try:
                logger.info("user [%s] found in LDAP", username)

                # Verify the shadow expire
                if self.check_shadow_expire:
                    shadow_expire = self._attr_shadow_expire(r)
                    # Convert nb. days into seconds.
                    if shadow_expire and shadow_expire * 24 * 60 * 60 < time.time():
                        logger.warn("user account %s expired: %s", username, shadow_expire)
                        raise RdiffError(_('User account %s expired.' % username))

                # Get username
                dn = r[0][0]
                new_username = self._decode(r[0][1][self.attribute][0])

                # Verify if the user is member of the required group
                if self.require_group:
                    value = dn if self.group_attribute_is_dn else new_username
                    logger.info("check if user [%s] is member of [%s]", value, self.require_group)
                    if not l.compare_s(self.require_group, self.group_attribute, value):
                        raise RdiffError(_('Permissions denied for user account %s.' % username))
            finally:
                l.unbind_s()
            # Return the username
            return new_username
开发者ID:ikus060,项目名称:rdiffweb,代码行数:34,代码来源:__init__.py

示例4: render_prefs_panel

    def render_prefs_panel(self, panelid, **kwargs):  # @UnusedVariable
        # Get user root directory
        user_root = self.app.userdb.get_user_root(self.app.currentuser.username)
        user_root_b = encode_s(user_root)
        filename = os.path.join(user_root_b, b'.ssh', b'authorized_keys')

        # Handle action
        params = {}
        if 'action' in kwargs:
            try:
                action = kwargs['action']
                if action == 'add':
                    self._handle_add(filename, **kwargs)
                elif action == 'delete':
                    self._handle_delete(filename, **kwargs)
            except ValueError as e:
                params['error'] = unicode(e)
            except Exception as e:
                _logger.warn("unknown error processing action", exc_info=True)
                params['error'] = _("Unknown error")

        # Get SSH keys if file exists.
        params["sshkeys"] = []
        if os.access(filename, os.R_OK):
            try:
                params["sshkeys"] = [
                    {'title': key.comment or (key.keytype + ' ' + key.key[:18]),
                     'fingerprint': key.fingerprint,
                     'lineno': key.lineno}
                    for key in authorizedkeys.read(filename)]
            except IOError:
                params['error'] = _("error reading SSH keys file")
                _logger.warn("error reading SSH keys file [%s]", filename)

        return "prefs_sshkeys.html", params
开发者ID:fliphess,项目名称:rdiffweb,代码行数:35,代码来源:__init__.py

示例5: _users_handle_action

    def _users_handle_action(self, action, username, email, password,
                             user_root, is_admin):

        success = ""

        # We need to change values. Change them, then give back that main
        # page again, with a message
        if username == self.app.currentuser.username:
            # Don't allow the user to changes it's "admin" state.
            is_admin = self.app.currentuser.is_admin

        is_admin = str(is_admin).lower() in ['true', '1']

        # Fork the behaviour according to the action.
        if action == "edit":
            user = self.app.userdb.get_user(username)
            logger.info("updating user [%s] info", user)
            if password:
                self.app.userdb.set_password(username, password, old_password=None)
            user.user_root = user_root
            user.is_admin = is_admin
            # Avoid updating the email fields is it didn'T changed. see pdsl/minarca#187
            if email != user.email:
                user.email = email
            success = _("User information modified successfully.")

            # Check and update user directory
            self._check_user_root_dir(user_root)
            rdw_spider_repos.find_repos_for_user(user)

        elif action == "add":

            if username == "":
                raise RdiffWarning(_("The username is invalid."))
            logger.info("adding user [%s]", username)

            user = self.app.userdb.add_user(username, password)
            user.user_root = user_root
            user.is_admin = is_admin
            user.email = email

            # Check and update user directory
            self._check_user_root_dir(user_root)
            rdw_spider_repos.find_repos_for_user(user)
            success = _("User added successfully.")

        if action == "delete":
            user = self.app.userdb.get_user(username)
            if username == self.app.currentuser.username:
                raise RdiffWarning(_("You cannot remove your own account!."))
            logger.info("deleting user [%s]", username)
            self.app.userdb.delete_user(user)
            success = _("User account removed.")

        # Return messages
        return {'success': success}
开发者ID:ikus060,项目名称:rdiffweb,代码行数:56,代码来源:page_admin.py

示例6: _handle_set_encoding

    def _handle_set_encoding(self, repo_obj, **kwargs):
        """
        Change the encoding of the repository.
        """
        # Validate the encoding value
        new_encoding = kwargs.get('encoding')
        new_encoding = unicode(encodings.normalize_encoding(new_encoding)).lower()
        if new_encoding not in self._get_encodings():
            raise ValueError(_("invalid encoding value"))

        # Update the repository encoding
        _logger.info("updating repository [%s] encoding [%s]", repo_obj, new_encoding)
        repo_obj.set_encoding(new_encoding)

        return {'success': _("Repository updated successfully with new encoding.")}
开发者ID:fliphess,项目名称:rdiffweb,代码行数:15,代码来源:page_settings.py

示例7: set_password

 def set_password(self, user, password, old_password=None):
     # Check if user exists in database
     db = self.find_user_database(user)
     if not db:
         raise InvalidUserError(user)
     # Try to update the user password.
     store = self.find_user_store(user)
     if store and not store.supports('set_password'):
         raise RdiffError(_("""The authentication backend for user %s does
         not support setting the password""" % user))
     elif not store:
         store = self._get_supporting_store('set_password')
     if not store:
         raise RdiffError(_("none of the IPasswordStore supports setting the password"))
     store.set_password(user, password, old_password)
     self._notify('password_changed', user, password)
开发者ID:fliphess,项目名称:rdiffweb,代码行数:16,代码来源:user.py

示例8: index

    def index(self, path=b"", limit='10', **kwargs):
        self.assertIsInstance(path, bytes)
        self.assertIsInt(limit)
        limit = int(limit)

        logger.debug("history [%r]", path)

        repo_obj = self.validate_user_path(path)[0]
        assert isinstance(repo_obj, librdiff.RdiffRepo)

        # Set up warning about in-progress backups, if necessary
        warning = False
        status = repo_obj.status
        if status[0] != 'ok':
            warning = status[1] + ' ' + _("The displayed data may be inconsistent.")

        parms = {
            "limit": limit,
            "repo_name": repo_obj.display_name,
            "repo_path": repo_obj.path,
            "history_entries": repo_obj.get_history_entries(numLatestEntries=limit, reverse=True),
            "warning": warning,
        }

        return self._compile_template("history.html", **parms)
开发者ID:ikus060,项目名称:rdiffweb,代码行数:25,代码来源:page_history.py

示例9: send_notifications

    def send_notifications(self):
        """
        Loop trough all the user repository and send notifications.
        """

        now = librdiff.RdiffTime()

        def _user_repos():
            """Return a generator trought user repos to be notified."""
            for user in self.app.userdb.list():
                # Check if user has email.
                if not user.email:
                    continue
                # Identify old repo for current user.
                old_repos = []
                for repo in user.repo_list:
                    # Check if repo has age configured (in days)
                    maxage = repo.maxage
                    if not maxage or maxage <= 0:
                        continue
                    # Check repo age.
                    r = librdiff.RdiffRepo(user.user_root, repo.name)
                    if r.last_backup_date < (now - datetime.timedelta(days=maxage)):
                        old_repos.append(r)
                # Return an item only if user had old repo
                if old_repos:
                    yield user, old_repos

        # For each candidate, send mail.
        for user, repos in _user_repos():
            parms = {'user': user, 'repos': repos}
            self.send_mail(user, _('Notification'), 'email_notification.html', **parms)
开发者ID:ikus060,项目名称:rdiffweb,代码行数:32,代码来源:__init__.py

示例10: users

    def users(self, userfilter=u"", usersearch=u"", action=u"", username=u"",
              email=u"", password=u"", user_root=u"", is_admin=u""):

        # Check if user is an administrator
        if not self.app.currentuser or not self.app.currentuser.is_admin:
            raise cherrypy.HTTPError(403)

        self.assertIsInstance(userfilter, str)
        self.assertIsInstance(usersearch, str)

        # If we're just showing the initial page, just do that
        params = {}
        if self._is_submit():
            try:
                params = self._users_handle_action(action, username,
                                                   email, password, user_root,
                                                   is_admin)
            except RdiffWarning as e:
                params['warning'] = str(e)
            except RdiffError as e:
                params['error'] = str(e)
            except Exception as e:
                logger.warning("unknown error", exc_info=True)
                params['error'] = _("Unknown error")

        # Get page parameters
        params.update(
            self._users_get_params_for_page(userfilter, usersearch))

        # Build users page
        return self._compile_template("admin_users.html", **params)
开发者ID:ikus060,项目名称:rdiffweb,代码行数:31,代码来源:page_admin.py

示例11: render_prefs_panel

    def render_prefs_panel(self, panelid, **kwargs):  # @UnusedVariable
        # Process the parameters.
        params = dict()
        action = kwargs.get('action')
        if action:
            try:
                if action == "set_notification_info":
                    self._handle_set_notification_info(**kwargs)
                else:
                    _logger.info("unknown action: %s", action)
                    raise cherrypy.NotFound("Unknown action")
            except RdiffWarning as e:
                params['warning'] = str(e)
            except RdiffError as e:
                params['error'] = str(e)
            except Exception as e:
                _logger.warning("unknown error processing action", exc_info=True)
                params['error'] = _("Unknown error")

        params.update({
            'email': self.app.currentuser.email,
            'repos': [
                {'name': r.name, 'maxage': r.maxage}
                for r in self.app.currentuser.repo_list],
        })
        return "prefs_notification.html", params
开发者ID:ikus060,项目名称:rdiffweb,代码行数:26,代码来源:__init__.py

示例12: _handle_delete

    def _handle_delete(self, filename, **kwargs):
        """
        Called for delete a key from an authorized_keys file.
        """

        # Check if key is valid.
        if 'key' not in kwargs:
            raise ValueError(_("key is missing"))
        try:
            lineno = int(kwargs['key'])
        except ValueError:
            raise ValueError(_("key is invalid"))

        # Remove the key
        _logger.info("removing key [%s] from [%s]", lineno, filename)
        authorizedkeys.remove(filename, lineno)
开发者ID:fliphess,项目名称:rdiffweb,代码行数:16,代码来源:__init__.py

示例13: set_password

    def set_password(self, username, password, old_password=None):
        """Update the password of the given user."""
        assert isinstance(username, unicode)
        assert old_password is None or isinstance(old_password, unicode)
        assert isinstance(password, unicode)

        # Do nothing if password is empty
        if not password:
            raise ValueError(_("password can't be empty"))
        # Check if users are allowed to change their password in LDAP.
        if not self.allow_password_change:
            raise RdiffError(_("LDAP users are not allowed to change their password."))

        # Check if old_password id valid
        if old_password and not self.are_valid_credentials(username, old_password):
            raise ValueError(_("wrong password"))

        # Update the username password of the given user. If possible.
        return self._set_password_in_ldap(username, old_password, password)
开发者ID:fliphess,项目名称:rdiffweb,代码行数:19,代码来源:__init__.py

示例14: user_password_changed

    def user_password_changed(self, username, password):
        """
        Implementation of IUserChangeListener interface.
        """

        # get User object (to get email)
        userobj = self.app.userdb.get_user(username)
        assert userobj
        # If the email attributes was changed, send a mail notification.
        self.send_mail(userobj, _("Password changed"), "password_changed.html")
开发者ID:ikus060,项目名称:rdiffweb,代码行数:10,代码来源:__init__.py

示例15: _handle_set_password

    def _handle_set_password(self, **kwargs):
        """
        Called when changing user password.
        """
        if 'current' not in kwargs or not kwargs['current']:
            raise ValueError(_("current password is missing"))
        if 'new' not in kwargs or not kwargs['new']:
            raise ValueError(_("new password is missing"))
        if 'confirm' not in kwargs or not kwargs['confirm']:
            raise ValueError(_("confirmation password is missing"))

        # Check if confirmation is valid.
        if kwargs['new'] != kwargs['confirm']:
            return {'error': _("The new password and its confirmation does not matches.")}

        # Update user password
        user = self.app.currentuser.username
        _logger.info("updating user [%s] password", user)
        self.app.userdb.set_password(user, kwargs['new'], old_password=kwargs['current'])
        return {'success': _("Password updated successfully.")}
开发者ID:fliphess,项目名称:rdiffweb,代码行数:20,代码来源:__init__.py


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