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


Python defer.returnValue函数代码示例

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


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

示例1: on_GET

    def on_GET(self, origin, _content, query, context, user_id):
        """
        Args:
            origin (unicode): The authenticated server_name of the calling server

            _content (None): (GETs don't have bodies)

            query (dict[bytes, list[bytes]]): Query params from the request.

            **kwargs (dict[unicode, unicode]): the dict mapping keys to path
                components as specified in the path match regexp.

        Returns:
            Deferred[(int, object)|None]: either (response code, response object) to
                 return a JSON response, or None if the request has already been handled.
        """
        versions = query.get(b'ver')
        if versions is not None:
            supported_versions = [v.decode("utf-8") for v in versions]
        else:
            supported_versions = ["1"]

        content = yield self.handler.on_make_join_request(
            origin, context, user_id,
            supported_versions=supported_versions,
        )
        defer.returnValue((200, content))
开发者ID:matrix-org,项目名称:synapse,代码行数:27,代码来源:server.py

示例2: _sourcedirIsUpdatable

    def _sourcedirIsUpdatable(self):
        myFileWriter = StringFileWriter()
        args = {
                'workdir': self.build.path_module.join(self.workdir, 'CVS'),
                'writer': myFileWriter,
                'maxsize': None,
                'blocksize': 32*1024,
                }

        cmd = buildstep.RemoteCommand('uploadFile',
                dict(slavesrc='Root', **args),
                ignore_updates=True)
        yield self.runCommand(cmd)
        if cmd.rc is not None and cmd.rc != 0:
            defer.returnValue(False)
            return
        if myFileWriter.buffer.strip() != self.cvsroot:
            defer.returnValue(False)
            return

        myFileWriter.buffer = ""
        cmd = buildstep.RemoteCommand('uploadFile',
                dict(slavesrc='Repository', **args),
                ignore_updates=True)
        yield self.runCommand(cmd)
        if cmd.rc is not None and cmd.rc != 0:
            defer.returnValue(False)
            return
        if myFileWriter.buffer.strip() != self.cvsmodule:
            defer.returnValue(False)
            return

        defer.returnValue(True)
开发者ID:davidag,项目名称:buildbot,代码行数:33,代码来源:cvs.py

示例3: _do_password

    def _do_password(self, request, register_json, session):
        if (self.hs.config.enable_registration_captcha and
                not session[LoginType.RECAPTCHA]):
            # captcha should've been done by this stage!
            raise SynapseError(400, "Captcha is required.")

        if ("user" in session and "user" in register_json and
                session["user"] != register_json["user"]):
            raise SynapseError(400, "Cannot change user ID during registration")

        password = register_json["password"].encode("utf-8")
        desired_user_id = (register_json["user"].encode("utf-8") if "user"
                          in register_json else None)
        if desired_user_id and urllib.quote(desired_user_id) != desired_user_id:
            raise SynapseError(
                400,
                "User ID must only contain characters which do not " +
                "require URL encoding.")
        handler = self.handlers.registration_handler
        (user_id, token) = yield handler.register(
            localpart=desired_user_id,
            password=password
        )

        if session[LoginType.EMAIL_IDENTITY]:
            yield handler.bind_emails(user_id, session["threepidCreds"])

        result = {
            "user_id": user_id,
            "access_token": token,
            "home_server": self.hs.hostname,
        }
        self._remove_session(session)
        defer.returnValue(result)
开发者ID:gitter-badger,项目名称:synapse,代码行数:34,代码来源:register.py

示例4: performAction

    def performAction(self, req):
        authz = self.getAuthz(req)
        res = yield authz.actionAllowed('stopAllBuilds', req)
        if not res:
            defer.returnValue(path_to_authzfail(req))
            return

        builders = None
        if self.selectedOrAll == 'all':
            builders = self.status.getBuilderNames()
        elif self.selectedOrAll == 'selected':
            builders = [b for b in req.args.get("selected", []) if b]

        for bname in builders:
            builder_status = self.status.getBuilder(bname)
            (state, current_builds) = builder_status.getState()
            if state != "building":
                continue
            for b in current_builds:
                build_status = builder_status.getBuild(b.number)
                if not build_status:
                    continue
                build = StatusResourceBuild(build_status)
                build.stop(req, auth_ok=True)

        # go back to the welcome page
        defer.returnValue(path_to_root(req))
开发者ID:AbhishekKumarSingh,项目名称:buildbot,代码行数:27,代码来源:builder.py

示例5: force

    def force(self, req, builderNames):
        master = self.getBuildmaster(req)
        owner = self.getAuthz(req).getUsernameFull(req)
        schedulername = req.args.get("forcescheduler", ["<unknown>"])[0]
        if schedulername == "<unknown>":
            defer.returnValue((path_to_builder(req, self.builder_status),
                               "forcescheduler arg not found"))
            return

        args = {}
        # decode all of the args
        encoding = getRequestCharset(req)
        for name, argl in req.args.iteritems():
           if name == "checkbox":
               # damn html's ungeneric checkbox implementation...
               for cb in argl:
                   args[cb.decode(encoding)] = True
           else:
               args[name] = [ arg.decode(encoding) for arg in argl ]

        for sch in master.allSchedulers():
            if schedulername == sch.name:
                try:
                    yield sch.force(owner, builderNames, **args)
                    msg = ""
                except ValidationError, e:
                    msg = html.escape(e.message.encode('ascii','ignore'))
                break
开发者ID:AbhishekKumarSingh,项目名称:buildbot,代码行数:28,代码来源:builder.py

示例6: rebuildBuild

    def rebuildBuild(self, bs, reason="<rebuild, no reason given>", extraProperties=None):
        if not bs.isFinished():
            return

        # Make a copy of the properties so as not to modify the original build.
        properties = Properties()
        # Don't include runtime-set properties in a rebuild request
        properties.updateFromPropertiesNoRuntime(bs.getProperties())
        if extraProperties is None:
            properties.updateFromProperties(extraProperties)

        properties_dict = dict((k,(v,s)) for (k,v,s) in properties.asList())
        ssList = bs.getSourceStamps(absolute=True)
        
        if ssList:
            sourcestampsetid = yield  ssList[0].getSourceStampSetId(self.control.master)
            dl = []
            for ss in ssList[1:]:
                # add defered to the list
                dl.append(ss.addSourceStampToDatabase(self.control.master, sourcestampsetid))
            yield defer.gatherResults(dl)

            bsid, brids = yield self.control.master.addBuildset(
                    builderNames=[self.original.name],
                    sourcestampsetid=sourcestampsetid, 
                    reason=reason, 
                    properties=properties_dict)
            defer.returnValue((bsid, brids))
        else:
            log.msg('Cannot start rebuild, rebuild has no sourcestamps for a new build')
            defer.returnValue(None)
开发者ID:AbhishekKumarSingh,项目名称:buildbot,代码行数:31,代码来源:builder.py

示例7: get_current_state

    def get_current_state(self, room_id, event_type=None, state_key=""):
        if event_type and state_key is not None:
            result = yield self.get_current_state_for_key(
                room_id, event_type, state_key
            )
            defer.returnValue(result)

        def f(txn):
            sql = (
                "SELECT event_id FROM current_state_events"
                " WHERE room_id = ? "
            )

            if event_type and state_key is not None:
                sql += " AND type = ? AND state_key = ? "
                args = (room_id, event_type, state_key)
            elif event_type:
                sql += " AND type = ?"
                args = (room_id, event_type)
            else:
                args = (room_id, )

            txn.execute(sql, args)
            results = txn.fetchall()

            return [r[0] for r in results]

        event_ids = yield self.runInteraction("get_current_state", f)
        events = yield self._get_events(event_ids, get_prev_content=False)
        defer.returnValue(events)
开发者ID:heavenlyhash,项目名称:synapse,代码行数:30,代码来源:state.py

示例8: stepDone

    def stepDone(self, results, step):
        """This method is called when the BuildStep completes. It is passed a
        status object from the BuildStep and is responsible for merging the
        Step's results into those of the overall Build."""

        terminate = False
        text = None
        if isinstance(results, tuple):
            results, text = results
        assert isinstance(results, type(SUCCESS)), "got %r" % (results,)
        summary = yield step.getBuildResultSummary()
        if 'build' in summary:
            text = [summary['build']]
        log.msg(" step '%s' complete: %s (%s)" % (step.name, statusToString(results), text))
        if text:
            self.text.extend(text)
            self.master.data.updates.setBuildStateString(self.buildid,
                                                         bytes2unicode(" ".join(self.text)))
        self.results, terminate = computeResultAndTermination(step, results,
                                                              self.results)
        if not self.conn:
            # force the results to retry if the connection was lost
            self.results = RETRY
            terminate = True
        defer.returnValue(terminate)
开发者ID:chapuni,项目名称:buildbot,代码行数:25,代码来源:build.py

示例9: register_agent_instance

    def register_agent_instance(self, agent, descriptor=None):
        """
        Client method to register a Agent Instance
        @param agent takes in the agent to create a class and register a new instrument
        @param descriptor The empty, partial or full storage area for additial,
            subclass-specific values.
        """
        assert ((descriptor == None) or
               (isinstance(descriptor, coi_resource_descriptions.AgentInstance)))

        if isinstance(agent, coi_resource_descriptions.AgentInstance):
            agent_resource = agent
            assert agent_resource.RegistryIdentity, 'Agent Resource must have a registry Identity'

        else:
            agent_instance = agent
            # Build a new description of this agent instance
            agent_resource = yield self.describe_instance(agent_instance, descriptor)

            found_sir = yield self.find_registered_agent_instance_from_description(agent_resource)
            if found_sir:
                assert len(found_sir) == 1
                defer.returnValue(found_sir[0])
            else:
                agent_resource.create_new_reference()
                agent_resource.set_lifecyclestate(dataobject.LCStates.developed)

        agent_resource = yield self.base_register_resource('register_agent_instance',agent_resource)
        defer.returnValue(agent_resource)
开发者ID:blazetopher,项目名称:ioncore-python,代码行数:29,代码来源:agent_registry.py

示例10: _fetch

    def _fetch(self, _):
        fetch_required = True

        # If the revision already exists in the repo, we dont need to fetch.
        if self.revision:
            rc = yield self._dovccmd(["cat-file", "-e", self.revision], abandonOnFailure=False)
            if rc == RC_SUCCESS:
                fetch_required = False

        if fetch_required:
            command = ["fetch", "-t", self.repourl, self.branch]
            # If the 'progress' option is set, tell git fetch to output
            # progress information to the log. This can solve issues with
            # long fetches killed due to lack of output, but only works
            # with Git 1.7.2 or later.
            if self.prog:
                command.append("--progress")

            yield self._dovccmd(command)

        if self.revision:
            rev = self.revision
        else:
            rev = "FETCH_HEAD"
        command = ["reset", "--hard", rev, "--"]
        abandonOnFailure = not self.retryFetch and not self.clobberOnFailure
        res = yield self._dovccmd(command, abandonOnFailure)

        # Rename the branch if needed.
        if res == RC_SUCCESS and self.branch != "HEAD":
            # Ignore errors
            yield self._dovccmd(["branch", "-M", self.branch], abandonOnFailure=False)

        defer.returnValue(res)
开发者ID:sdegrande,项目名称:buildbot,代码行数:34,代码来源:git.py

示例11: get_raw

    def get_raw(self, uri, args={}):
        """ Gets raw text from the given URI.

        Args:
            uri (str): The URI to request, not including query parameters
            args (dict): A dictionary used to create query strings, defaults to
                None.
                **Note**: The value of each key is assumed to be an iterable
                and *not* a string.
        Returns:
            Deferred: Succeeds when we get *any* 2xx HTTP response, with the
            HTTP body at text.
        Raises:
            On a non-2xx HTTP response. The response body will be used as the
            error message.
        """
        if len(args):
            query_bytes = urllib.urlencode(args, True)
            uri = "%s?%s" % (uri, query_bytes)

        response = yield self.request(
            "GET",
            uri.encode("ascii"),
            headers=Headers({
                b"User-Agent": [self.user_agent],
            })
        )

        body = yield preserve_context_over_fn(readBody, response)

        if 200 <= response.code < 300:
            defer.returnValue(body)
        else:
            raise CodeMessageException(response.code, body)
开发者ID:JigmeDatse,项目名称:synapse,代码行数:34,代码来源:client.py

示例12: parseCommitDescription

    def parseCommitDescription(self, _=None):
        if self.getDescription == False:  # dict() should not return here
            defer.returnValue(RC_SUCCESS)
            return

        cmd = ["describe"]
        if isinstance(self.getDescription, dict):
            for opt, arg in git_describe_flags:
                opt = self.getDescription.get(opt, None)
                arg = arg(opt)
                if arg:
                    cmd.extend(arg)
        # 'git describe' takes a commitish as an argument for all options
        # *except* --dirty
        if not any(arg.startswith("--dirty") for arg in cmd):
            cmd.append("HEAD")

        try:
            stdout = yield self._dovccmd(cmd, collectStdout=True)
            desc = stdout.strip()
            self.updateSourceProperty("commit-description", desc)
        except Exception:
            pass

        defer.returnValue(RC_SUCCESS)
开发者ID:sdegrande,项目名称:buildbot,代码行数:25,代码来源:git.py

示例13: uploadSources

 def uploadSources():
     for source in sources:
         result = yield self.startUpload(source, masterdest)
         if result == FAILURE:
             defer.returnValue(FAILURE)
             return
     defer.returnValue(SUCCESS)
开发者ID:MPanH,项目名称:buildbot,代码行数:7,代码来源:transfer.py

示例14: create_search_schema

 def create_search_schema(self, schema, content):
     if not (yield self.pb_search_admin()):
         raise NotImplementedError("Yokozuna administration is not "
                                   "supported for this version")
     with (yield self._getFreeTransport()) as transport:
         ret = yield transport.create_search_schema(schema,content)
         defer.returnValue(True)
开发者ID:eminarcissus,项目名称:riakasaurus,代码行数:7,代码来源:pbc_transport.py

示例15: ping

 def ping(self):
     """
     Check server is alive
     """
     with (yield self._getFreeTransport()) as transport:
         ret = yield transport.ping()
     defer.returnValue(ret == True)
开发者ID:eminarcissus,项目名称:riakasaurus,代码行数:7,代码来源:pbc_transport.py


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