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


Python utils._函数代码示例

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


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

示例1: user_password_reset_get_token

def user_password_reset_get_token(username):
    try:
        validate_username(_('Username'), username)
    except ValidationError as err:
        return validation_err_response(err)

    result_getuid = forum.user_get_uid(username)
    if result_getuid[0] != 0:
        return json_response(result_getuid)
    uid = result_getuid[2]['uid']

    result = forum.user_password_reset_get_token(uid)
    if result[0] != 0:
        return json_response(result)
    data = result[2]

    try:
        send_mail(
            subject = _('Password Reset - %s') % config['site_name'],
            addr_from = EMAIL_ADDRESS,
            addr_to = data['mail'],
            content = (
                _('Verification Code: %s (Valid in 90 minutes)')
                % data['token']
            )
        )
        del data['mail']
        del data['token']
        return json_response(result)
    except Exception as err:
        return json_response((253, _('Failed to send mail: %s') % str(err)) )
开发者ID:910JQK,项目名称:linuxbar,代码行数:31,代码来源:app.py

示例2: set_parent

    def set_parent(self,parent_name):
        """
        Instead of a --distro, set the parent of this object to another profile
        and use the values from the parent instead of this one where the values
        for this profile aren't filled in, and blend them together where they
        are hashes.  Basically this enables profile inheritance.  To use this,
        the object MUST have been constructed with is_subobject=True or the
        default values for everything will be screwed up and this will likely NOT
        work.  So, API users -- make sure you pass is_subobject=True into the
        constructor when using this.
        """

        old_parent = self.get_parent()
        if isinstance(old_parent, item.Item):
            old_parent.children.pop(self.name, 'pass')
        if parent_name is None or parent_name == '':
           self.parent = ''
           return True
        if parent_name == self.name:
           # check must be done in two places as set_parent could be called before/after
           # set_name...
           raise CX(_("self parentage is weird"))
        found = self.config.profiles().find(name=parent_name)
        if found is None:
           raise CX(_("profile %s not found, inheritance not possible") % parent_name)
        self.parent = parent_name       
        self.depth = found.depth + 1
        parent = self.get_parent()
        if isinstance(parent, item.Item):
            parent.children[self.name] = self
        return True
开发者ID:lindenle,项目名称:cobbler,代码行数:31,代码来源:item_profile.py

示例3: check_dhcpd_conf

   def check_dhcpd_conf(self,status):
       """
       NOTE: this code only applies if cobbler is *NOT* set to generate
       a dhcp.conf file

       Check that dhcpd *appears* to be configured for pxe booting.
       We can't assure file correctness.  Since a cobbler user might
       have dhcp on another server, it's okay if it's not there and/or
       not configured correctly according to automated scans.
       """
       if not (self.settings.manage_dhcp == 0):
           return

       if os.path.exists(self.settings.dhcpd_conf):
           match_next = False
           match_file = False
           f = open(self.settings.dhcpd_conf)
           for line in f.readlines():
               if line.find("next-server") != -1:
                   match_next = True
               if line.find("filename") != -1:
                   match_file = True
           if not match_next:
              status.append(_("expecting next-server entry in %(file)s") % { "file" : self.settings.dhcpd_conf })
           if not match_file:
              status.append(_("missing file: %(file)s") % { "file" : self.settings.dhcpd_conf })
       else:
           status.append(_("missing file: %(file)s") % { "file" : self.settings.dhcpd_conf })
开发者ID:77720616,项目名称:cobbler,代码行数:28,代码来源:action_check.py

示例4: doActionFor

    def doActionFor(self, ob, action, wf_id=None, *args, **kw):

        """ Execute the given workflow action for the object.

        o Invoked by user interface code.

        o Allows the user to request a workflow action.

        o The workflow object must perform its own security checks.
        """
        wfs = self.getWorkflowsFor(ob)
        if wfs is None:
            wfs = ()
        if wf_id is None:
            if not wfs:
                raise WorkflowException(_(u'No workflows found.'))
            found = 0
            for wf in wfs:
                if wf.isActionSupported(ob, action, **kw):
                    found = 1
                    break
            if not found:
                msg = _(u"No workflow provides the '${action_id}' action.",
                        mapping={'action_id': action})
                raise WorkflowException(msg)
        else:
            wf = self.getWorkflowById(wf_id)
            if wf is None:
                raise WorkflowException(
                    _(u'Requested workflow definition not found.'))
        return self._invokeWithNotification(
            wfs, ob, action, wf.doActionFor, (ob, action) + args, kw)
开发者ID:goschtl,项目名称:zope,代码行数:32,代码来源:WorkflowTool.py

示例5: auto_add_repos

    def auto_add_repos(self):
        """
        Import any repos this server knows about and mirror them.
        Credit: Seth Vidal.
        """
        self.log("auto_add_repos")
        try:
            import yum
        except:
            raise CX(_("yum is not installed"))

        version = yum.__version__
        (a,b,c) = version.split(".")
        version = a* 1000 + b*100 + c
        if version < 324:
            raise CX(_("need yum > 3.2.4 to proceed"))

        base = yum.YumBase()
        base.doRepoSetup()
        repos = base.repos.listEnabled()
        if len(repos) == 0:
            raise CX(_("no repos enabled/available -- giving up."))

        for repo in repos:
            url = repo.urls[0]
            cobbler_repo = self.new_repo()
            auto_name = repo.name.replace(" ","")
            # FIXME: probably doesn't work for yum-rhn-plugin ATM
            cobbler_repo.set_mirror(url)
            cobbler_repo.set_name(auto_name)
            print "auto adding: %s (%s)" % (auto_name, url)
            self._config.repos().add(cobbler_repo,save=True)

        # run cobbler reposync to apply changes
        return True 
开发者ID:ciupicri,项目名称:cobbler,代码行数:35,代码来源:api.py

示例6: doActionFor

 def doActionFor(self, ob, action, wf_id=None, *args, **kw):
     """ Perform the given workflow action on 'ob'.
     """
     wfs = self.getWorkflowsFor(ob)
     if wfs is None:
         wfs = ()
     if wf_id is None:
         if not wfs:
             raise WorkflowException(_(u'No workflows found.'))
         found = 0
         for wf in wfs:
             if wf.isActionSupported(ob, action, **kw):
                 found = 1
                 break
         if not found:
             msg = _(u"No workflow provides the '${action_id}' action.",
                     mapping={'action_id': action})
             raise WorkflowException(msg)
     else:
         wf = self.getWorkflowById(wf_id)
         if wf is None:
             raise WorkflowException(
                 _(u'Requested workflow definition not found.'))
     return self._invokeWithNotification(
         wfs, ob, action, wf.doActionFor, (ob, action) + args, kw)
开发者ID:goschtl,项目名称:zope,代码行数:25,代码来源:WorkflowTool.py

示例7: on_build_installer_clicked

    def on_build_installer_clicked(self):
        # First of all, check that it's valid.
        package = self.window.package
        package.validate()

        if len(package.errors):
            QtGui.QMessageBox.critical(self,
                    _('PortableApps.com Development Toolkit'),
                    _('There are errors in the package. You must fix them before making a release.'),
                    QtGui.QMessageBox.Ok)
            self.window.set_page('test')
            self.window.page_test.go_to_tab('validate')
            return
        elif len(package.warnings):
            answer = QtGui.QMessageBox.warning(self,
                    _('PortableApps.com Development Toolkit'),
                    _('There are warnings in the package validation. You should fix them before making a release.'),
                    QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ignore)
            if answer == QtGui.QMessageBox.Cancel:
                self.window.set_page('test')
                self.window.page_test.go_to_tab('validate')
                return

        if self.window.page_options.find_installer_path():
            # If not found, user told about it in find_installer_path

            self._installer_thread = InstallerThread(self)
            self._installer_thread.update_contents_async.connect(self.update_contents_async)
            self._installer_thread.start()
开发者ID:3D1T0R,项目名称:PortableApps.com-DevelopmentToolkit,代码行数:29,代码来源:publish.py

示例8: page1

def page1(ctx):
    field_username = "login_username"
    place_username = _("Username")

    field_password = "login_password"
    place_password = _("Password")
    with DIV.container_fluid as out:
        with DIV.row_fluid:
            with FORM(id="login_form",align="center"):
                H1(ctx.get('company','Company'),align="center")
                BR()
                with FIELDSET:
                    with DIV.span6.offset3:
                        with DIV.row_fluid:
                            with DIV.span5.offset1.pull_left:
                                LABEL(place_username,for_=field_username)
                                with DIV.control_group:
                                    with DIV.controls:
                                        with DIV.input_prepend:
                                            with SPAN.add_on:
                                                I("",class_="icon-user")
                                            INPUT(type='text',placeholder=place_username,id=field_username)
                            with DIV.span5.pull_right:
                                LABEL(place_password,for_=field_password)
                                with DIV.control_group:
                                    with DIV.controls:
                                        INPUT(type='password',placeholder=place_password,id=field_password)
                        with DIV.row_fluid:
                            with DIV(align="center").span4.offset4:
                                BUTTON(_("Login"),type="button",align="center",class_="btn btn-success btn-large")

                with DIV(align="center"):
                    H3(_("Don't you have an account?"))
                    A(_("Register"),type="button",href="#", class_="btn btn-primary btn-large")
开发者ID:kostyll,项目名称:usb-flash-network-monitor,代码行数:34,代码来源:web_face_gen_templatete.py

示例9: freeNodes

 def freeNodes(self,relpath):
     #causing problems
     """Free up nodes corresponding to file, if possible"""
     bnode = self.basenodes.get(relpath,None)
     if bnode is None:
         print "Missing node for %s" % relpath
         return
     bnode.unlinkNode()
     bnode.freeNode()
     del self.basenodes[relpath]
     pkgid = self.pkg_ids.get(relpath,None)
     if pkgid is None:
         print _("No pkgid found for: %s") % relpath
         return None
     del self.pkg_ids[relpath]
     dups = self.pkgrefs.get(pkgid)
     dups.remove(relpath)
     if len(dups):
         #still referenced
         return
     del self.pkgrefs[pkgid]
     for nodes in self.filesnodes, self.othernodes:
         node = nodes.get(pkgid)
         if node is not None:
             node.unlinkNode()
             node.freeNode()
             del nodes[pkgid]
开发者ID:stefanozanella,项目名称:createrepo,代码行数:27,代码来源:readMetadata.py

示例10: project_view

def project_view(project_code):
    project = db.Project.get_by_code(project_code)
    xrecords, urecords = [], []

    for f in project.xforms:
        xform = db.XForm.get_by_id(f)
        record = _(id=xform.id_string, title=xform.title)
        captures = db.Capture.get_by_form(f, False)
        if captures.count():
            summary = stats.activity_summary(captures)
            record.update(summary)
        xrecords.append(record)

    for f in project.uforms:
        uform = db.XForm.get_by_id(f)
        record = _(id=uform.id_string, title=uform.title)
        updates = db.Update.get_by_form(f, False)
        if updates.count():
            summary = stats.activity_summary(updates)
            record.update(summary)
        urecords.append(record)

    return {
        'title': 'Project: %s' % project.name,
        'project': project,
        'xrecords': xrecords,
        'urecords': urecords
    }
开发者ID:hkmshb,项目名称:centrackb,代码行数:28,代码来源:core.py

示例11: index

def index():
    #+==========================
    #: forms series summary
    records = []
    projects = db.Project.get_all()
    ref_date = _get_ref_date()
    wkdate_bounds = get_weekdate_bounds

    for p in projects:
        record = _(code=p.code, name=p.name)
        captures = db.Capture.get_by_project(p.code, paginate=False)
        if captures.count():
            summary = stats.series_purity_summary(captures, ref_date)
            record.update(summary)
        records.append(record)

    #+==========================
    #: today activity summary
    activity_summary, activity_stats = [], _()
    captures = list(db.Capture.get_by_date(ref_date.isoformat(), paginate=False))
    if captures:
        activity_stats = stats.day_activity_stats(captures, ref_date)
        activity_breakdown = stats.day_activity_breakdown(captures, ref_date)
        for record in activity_breakdown:
            activity_summary.append(_(record))

    return {
        'is_front': True, 
        'title': 'Capture Summary',
        'records': records,
        'activity_records': activity_summary,
        'activity_stats': activity_stats,
        'report_ref_date': ref_date,
        'report_weekdate_bounds': wkdate_bounds,
    }
开发者ID:hkmshb,项目名称:centrackb,代码行数:35,代码来源:core.py

示例12: TriggerEvent

	def TriggerEvent(self, function, args):
		"""Triggers an event for the plugins. Since events and notifications
		are precisely the same except for how n+ responds to them, both can be
		triggered by this function."""
		hotpotato = args
		for module, plugin in self.enabled_plugins.items():
			try:
				func = eval("plugin.PLUGIN." + function)
				ret = func(*hotpotato)
				if ret != None and type(ret) != tupletype:
					if ret == returncode['zap']:
						return None
					elif ret == returncode['break']:
						return hotpotato
					elif ret == returncode['pass']:
						pass
					else:
						log.add(_("Plugin %(module) returned something weird, '%(value)', ignoring") % {'module':module, 'value':ret})
				if ret != None:
					hotpotato = ret
			except:
				log.add(_("Plugin %(module)s failed with error %(errortype)s: %(error)s.\nTrace: %(trace)s\nProblem area:%(area)s") %
					{'module':module,
					'errortype':sys.exc_info()[0],
					'error':sys.exc_info()[1],
					'trace':''.join(format_list(extract_stack())),
					'area':''.join(format_list(extract_tb(sys.exc_info()[2])))})
		return hotpotato
开发者ID:Steeler77,项目名称:nicotine-plus,代码行数:28,代码来源:pluginsystem.py

示例13: topic_add

def topic_add():
    board = request.form.get('board', '')
    title = request.form.get('title', '')
    content = request.form.get('content', '')
    if not content:
        content = title
    s_len = SUMMARY_LENGTH
    summary = (content[:s_len-3] + '...') if len(content) > s_len else content
    try:
        validate_board(_('Board Name'), board)
        validate(_('Title'), title, max=64, not_empty=True)
    except ValidationError as err:
        return validation_err_response(err)
    uid = session.get('uid')
    if not uid:
        return json_response((249, _('Not signed in.')) )

    result_ban_global = forum.ban_check(uid)
    if result_ban_global[0] != 0:
        return json_response(result_ban_global)
    result_ban_local = forum.ban_check(uid, board)
    if result_ban_local[0] != 0:
        return json_response(result_ban_local)

    if result_ban_global[2]['banned'] or result_ban_local[2]['banned']:
        return json_response((252, _('You are being banned.')) )

    return json_response(forum.topic_add(board, title, uid, summary, content))
开发者ID:910JQK,项目名称:linuxbar,代码行数:28,代码来源:app.py

示例14: admin_add

def admin_add(uid):
    board = request.args.get('board', '')
    level = request.args.get('level', '1')
    try:
        validate_board(_('Board Name'), board)
        validate_uint(_('Administrator Level'), level)
    except ValidationError as err:
        return validation_err_response(err)

    operator = session.get('uid')
    if not operator:
        return json_response((254, _('Permission denied.')) )

    if level == '0':
        check = forum.admin_check(operator)
        if check[0] != 0:
            return json_response(check)
        if check[2]['admin']:
            return json_response(forum.admin_add(uid, board, int(level)) )
        else:
            return json_response((254, _('Permission denied.')) )
    else:
        check_site = forum.admin_check(operator)
        check_board = forum.admin_check(operator, board)
        if check_site[0] != 0:
            return json_response(check_site)
        if check_board[0] != 0:
            return json_response(check_board)
        if (
                check_site[2]['admin']
                or (check_board[2]['admin'] and check_board[2]['level'] == 0)
            ):
            return json_response(forum.admin_add(uid, board, int(level)) )
        else:
            return json_response((254, _('Permission denied.')) )
开发者ID:910JQK,项目名称:linuxbar,代码行数:35,代码来源:app.py

示例15: set_network

    def set_network(self,network,interface):
        """
        Add an interface to a network object.  If network is empty,
        clear the network.
        """
        intf = self.__get_interface(interface)

        if network == intf['network']:
            # setting the existing network is no-op
            return

        if intf['network'] != '':
            # we are currently subscribed to a network, so to join
            # a different one we need to leave this one first.
            net = self.config.networks().find(name=intf['network'])
            if net == None:
                raise CX(_("Network %s does not exist" % network))
            net.unsubscribe_system(self.name, interface)
            intf['network'] = ''

        if network != '': # Join
            net  = self.config.networks().find(name=network)
            if net == None:
                raise CX(_("Network %s does not exist" % network))
            net.subscribe_system(self.name, interface, intf['ip_address'])
            intf['network'] = network

        # FIXME figure out why the network collection doesn't
        # serialize itself out to disk without this
        self.config.serialize()
开发者ID:javiplx,项目名称:cobbler-debian,代码行数:30,代码来源:item_system.py


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