• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils._函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: scp_it

 def scp_it(self,from_path,to_path):
     from_path = "%s:%s" % (self.host, from_path)
     cmd = "scp %s %s" % (from_path, to_path)
     print _("- %s") % cmd
     rc = sub_process.call(cmd, shell=True, close_fds=True)
     if rc !=0:
         raise CX(_("scp failed"))
开发者ID:icontender,项目名称:cobbler,代码行数:7,代码来源:action_replicate.py


示例17: __get_interface

    def __get_interface(self, name):

        if name == "" and len(self.interfaces.keys()) == 0:
            raise CX(_("No interfaces defined. Please use --interface <interface_name>"))
        elif name == "" and len(self.interfaces.keys()) == 1:
            name = self.interfaces.keys()[0]
        elif name == "" and len(self.interfaces.keys()) > 1:
            raise CX(_("Multiple interfaces defined. Please use --interface <interface_name>"))
        elif name not in self.interfaces:
            self.interfaces[name] = {
                "mac_address": "",
                "mtu": "",
                "ip_address": "",
                "dhcp_tag": "",
                "netmask": "",
                "if_gateway": "",
                "virt_bridge": "",
                "static": False,
                "interface_type": "",
                "interface_master": "",
                "bonding_opts": "",
                "bridge_opts": "",
                "management": False,
                "dns_name": "",
                "static_routes": [],
                "ipv6_address": "",
                "ipv6_secondaries": [],
                "ipv6_mtu": "",
                "ipv6_static_routes": [],
                "ipv6_default_gateway": "",
                "cnames": [],
            }

        return self.interfaces[name]
开发者ID:sroegner,项目名称:cobbler,代码行数:34,代码来源:item_system.py


示例18: check_yum

    def check_yum(self, status):
        if self.checked_dist in ["debian", "ubuntu"]:
            return

        if not os.path.exists("/usr/bin/createrepo"):
            status.append(
                _(
                    "createrepo package is not installed, needed for cobbler import and cobbler reposync, install createrepo?"
                )
            )
        if not os.path.exists("/usr/bin/reposync"):
            status.append(_("reposync is not installed, need for cobbler reposync, install/upgrade yum-utils?"))
        if not os.path.exists("/usr/bin/yumdownloader"):
            status.append(
                _(
                    "yumdownloader is not installed, needed for cobbler repo add with --rpm-list parameter, install/upgrade yum-utils?"
                )
            )
        if self.settings.reposync_flags.find("-l"):
            if self.checked_dist == "redhat" or self.checked_dist == "suse":
                yum_utils_ver = utils.subprocess_get(
                    self.logger, "/usr/bin/rpmquery --queryformat=%{VERSION} yum-utils", shell=True
                )
                if yum_utils_ver < "1.1.17":
                    status.append(
                        _("yum-utils need to be at least version 1.1.17 for reposync -l, current version is %s")
                        % yum_utils_ver
                    )
开发者ID:shenson,项目名称:cobbler,代码行数:28,代码来源:action_check.py


示例19: getInfoFor

 def getInfoFor(self, ob, name, default=_marker, wf_id=None, *args, **kw):
     """ Get the given bit of workflow information for the object.
     """
     if wf_id is None:
         wfs = self.getWorkflowsFor(ob)
         if wfs is None:
             if default is _marker:
                 raise WorkflowException(_(u'No workflows found.'))
             else:
                 return default
         found = 0
         for wf in wfs:
             if wf.isInfoSupported(ob, name):
                 found = 1
                 break
         if not found:
             if default is _marker:
                 msg = _(u"No workflow provides '${name}' information.",
                         mapping={'name': name})
                 raise WorkflowException(msg)
             else:
                 return default
     else:
         wf = self.getWorkflowById(wf_id)
         if wf is None:
             if default is _marker:
                 raise WorkflowException(
                     _(u'Requested workflow definition not found.'))
             else:
                 return default
     res = wf.getInfoFor(ob, name, default, *args, **kw)
     if res is _marker:
         msg = _(u'Could not get info: ${name}', mapping={'name': name})
         raise WorkflowException(msg)
     return res
开发者ID:goschtl,项目名称:zope,代码行数:35,代码来源:WorkflowTool.py


示例20: needConfig

	def needConfig(self):
		errorlevel = 0
		try:
			for i in self.sections.keys():
				for j in self.sections[i].keys():
			# 		print self.sections[i][j]
					if type(self.sections[i][j]) not in [type(None), type("")]:
						continue
					if self.sections[i][j] is None or self.sections[i][j] == '' and i not in ("userinfo", "ui", "ticker", "players", "language") and j not in ("incompletedir", "autoreply", 'afterfinish', 'afterfolder', 'geoblockcc', 'downloadregexp', "language"):
						# Repair options set to None with defaults
						if self.sections[i][j] is None and self.defaults[i][j] is not None:
							self.sections[i][j] = self.defaults[i][j]
							self.frame.logMessage(_("Config option reset to default: Section: %(section)s, Option: %(option)s, to: %(default)s") % {'section':i, 'option':j, 'default':self.sections[i][j]})
							if errorlevel == 0:
								errorlevel = 1
						else:
							if errorlevel < 2:
								self.frame.logMessage(_("You need to configure your settings (Server, Username, Password, Download Directory) before connecting..."))
								errorlevel = 2
							
							self.frame.logMessage(_("Config option unset: Section: %(section)s, Option: %(option)s") % {'section':i, 'option':j})
							self.frame.settingswindow.InvalidSettings(i, j)
			
		except Exception, error:
			message = _("Config error: %s") % error
			self.frame.logMessage(message)
			if errorlevel < 3:
				errorlevel = 3
开发者ID:Steeler77,项目名称:nicotine-plus,代码行数:28,代码来源:config.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils._api_scrape函数代码示例发布时间:2022-05-26
下一篇:
Python utility_functions.extract_name函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap