本文整理汇总了Python中twisted.internet.defer.returnValue函数的典型用法代码示例。如果您正苦于以下问题:Python returnValue函数的具体用法?Python returnValue怎么用?Python returnValue使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了returnValue函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: _mergeRequests
def _mergeRequests(self, breq, unclaimed_requests, mergeRequests_fn):
"""Use C{mergeRequests_fn} to merge C{breq} against
C{unclaimed_requests}, where both are build request dictionaries"""
# short circuit if there is no merging to do
if not mergeRequests_fn or len(unclaimed_requests) == 1:
defer.returnValue([ breq ])
return
# we'll need BuildRequest objects, so get those first
unclaimed_request_objects = yield defer.gatherResults(
[ self._brdictToBuildRequest(brdict)
for brdict in unclaimed_requests ])
breq_object = unclaimed_request_objects[unclaimed_requests.index(breq)]
# gather the mergeable requests
merged_request_objects = []
for other_breq_object in unclaimed_request_objects:
if (yield defer.maybeDeferred(
lambda : mergeRequests_fn(self, breq_object,
other_breq_object))):
merged_request_objects.append(other_breq_object)
# convert them back to brdicts and return
merged_requests = [ br.brdict for br in merged_request_objects ]
defer.returnValue(merged_requests)
开发者ID:AbhishekKumarSingh,项目名称:buildbot,代码行数:26,代码来源:builder.py
示例17: update_counter
def update_counter(self, bucket, key, value, **params):
counters = yield self.counters()
if not counters:
raise NotImplementedError("Counters are not supported")
with (yield self._getFreeTransport()) as transport:
ret = yield transport.update_counter(bucket,key,value,**params)
defer.returnValue(ret)
开发者ID:eminarcissus,项目名称:riakasaurus,代码行数:7,代码来源:pbc_transport.py
示例18: mock_event
def mock_event(self, msg, nr_events):
self.mock_response(msg)
yield self.tx_helper.make_dispatch_outbound(
"foo", to_addr='2371234567', message_id='id_%s' % (msg,))
yield self.fake_cellulant.get()
events = yield self.tx_helper.wait_for_dispatched_events(nr_events)
returnValue(events)
开发者ID:AndrewCvekl,项目名称:vumi,代码行数:7,代码来源:test_cellulant_sms.py
示例19: update_datatype
def update_datatype(self, datatype, w=None, dw=None,
pw=None, return_body=None, timeout=None,
include_context=None,bucket_type = None):
"""
Updates a Riak Datatype. This operation is not idempotent and
so will not be retried automatically.
:param datatype: the datatype to update
:type datatype: a subclass of :class:`~riak.datatypes.Datatype`
:param w: the write quorum
:type w: integer, string, None
:param dw: the durable write quorum
:type dw: integer, string, None
:param pw: the primary write quorum
:type pw: integer, string, None
:param timeout: a timeout value in milliseconds
:type timeout: int
:param include_context: whether to return the opaque context
as well as the value, which is useful for removal operations
on sets and maps
:type include_context: bool
:rtype: a subclass of :class:`~riak.datatypes.Datatype`, bool
"""
with (yield self._getFreeTransport()) as transport:
result = yield transport.update_datatype(datatype,w=w,
dw=dw, pw=pw,
return_body=return_body,
timeout=timeout,
include_context=include_context)
defer.returnValue(result)
开发者ID:eminarcissus,项目名称:riakasaurus,代码行数:30,代码来源:pbc_transport.py
示例20: start
def start(self, fire_hooks=True, start_relations=True):
"""Invoke the start hook, and setup relation watching.
:param fire_hooks: False to skip running config-change and start hooks.
Will not affect any relation hooks that happen to be fired as a
consequence of starting up.
:param start_relations: True to transition all "down" relation
workflows to "up".
"""
self._log.debug("pre-start acquire, running:%s", self._running)
yield self._run_lock.acquire()
self._log.debug("start running, unit lifecycle")
watches = []
try:
if fire_hooks:
yield self._execute_hook("config-changed")
yield self._execute_hook("start")
if self._relations is None:
yield self._load_relations()
if start_relations:
# We actually want to transition from "down" to "up" where
# applicable (ie a stopped unit is starting up again)
for workflow in self._relations.values():
with (yield workflow.lock()):
state = yield workflow.get_state()
if state == "down":
yield workflow.transition_state("up")
# Establish a watch on the existing relations.
if not self._watching_relation_memberships:
self._log.debug("starting service relation watch")
watches.append(self._service.watch_relation_states(
self._on_service_relation_changes))
self._watching_relation_memberships = True
# Establish a watch for resolved relations
if not self._watching_relation_resolved:
self._log.debug("starting unit relation resolved watch")
watches.append(self._unit.watch_relation_resolved(
self._on_relation_resolved_changes))
self._watching_relation_resolved = True
# Set current status
self._running = True
finally:
self._run_lock.release()
# Give up the run lock before waiting on initial watch invocations.
results = yield DeferredList(watches, consumeErrors=True)
# If there's an error reraise the first one found.
errors = [e[1] for e in results if not e[0]]
if errors:
returnValue(errors[0])
self._log.debug("started unit lifecycle")
开发者ID:anbangr,项目名称:trusted-juju,代码行数:60,代码来源:lifecycle.py
注:本文中的twisted.internet.defer.returnValue函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论