本文整理汇总了Python中twisted.internet.defer.returnValue方法的典型用法代码示例。如果您正苦于以下问题:Python defer.returnValue方法的具体用法?Python defer.returnValue怎么用?Python defer.returnValue使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.defer
的用法示例。
在下文中一共展示了defer.returnValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render_GET
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def render_GET(self, request):
json, trigger = yield self.db.getTrigger(self.trigger_id)
if json is None:
defer.returnValue(bad_request(request, "Trigger not found"))
raise StopIteration
fromTime = request.args.get('from')[0]
endTime = request.args.get('to')[0]
context = createRequestContext(fromTime, endTime, allowRealTimeAlerting=True)
result = {}
for target in trigger.get("targets", [trigger.get("target")]):
time_series = yield evaluateTarget(context, target)
for time_serie in time_series:
values = [(time_serie.start + time_serie.step * i, time_serie[i]) for i in range(0, len(time_serie))]
result[time_serie.name] = [{"ts": ts, "value": value} for ts, value in values if value is not None]
self.write_json(request, result)
示例2: saveUserContact
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def saveUserContact(self, login, contact, existing=None):
"""
saveUserContact(self, login, contact)
Creates redis transaction for:
- save *contact* json to key {0}
- add *contact_id* to set {1}
:param login: user login
:type login: string
:param contact: contact data
:type contact: json dict
:rtype: json dict
"""
contact["user"] = login
contact_id = contact.get("id", str(uuid4()))
contact["id"] = contact_id
t = yield self.rc.multi()
yield t.set(CONTACT_PREFIX.format(contact_id), anyjson.serialize(contact))
yield t.sadd(USER_CONTACTS_PREFIX.format(login), contact_id)
yield t.commit()
defer.returnValue(contact)
示例3: getAllContacts
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def getAllContacts(self):
"""
getAllContacts(self, login)
Returns all contacts json
:rtype: array of strings
"""
result = []
keys = yield self.rc.keys(CONTACT_PREFIX.format('*'))
for key in keys:
contact_id = key.split(':')[-1]
contact = yield self.getContact(contact_id)
if contact:
result.append(contact)
defer.returnValue(result)
示例4: getSubscription
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def getSubscription(self, sub_id):
"""
getSubscription(self, sub_id)
Returns subscription by given id from key {0}
:param sub_id: subscription id
:type sub_id: string
:rtype: json dict
"""
sub_json = yield self.rc.get(SUBSCRIPTION_PREFIX.format(sub_id))
sub = None
if sub_json is not None:
sub = anyjson.loads(sub_json)
sub["id"] = sub_id
defer.returnValue(sub)
示例5: getContact
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def getContact(self, contact_id):
"""
getContact(self, contact_id)
Returns contact by given id from key {0}
:param contact_id: contact id
:type contact_id: string
:rtype: json dict
"""
contact_json = yield self.rc.get(CONTACT_PREFIX.format(contact_id))
contact = None
if contact_json is not None:
contact = anyjson.loads(contact_json)
contact["id"] = contact_id
defer.returnValue(contact)
示例6: getTagSubscriptions
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def getTagSubscriptions(self, tag):
"""
getTagSubscriptions(self, tag)
Returns all subscriptions by given tag from set {0}
:type tag: string
:rtype: list of strings
"""
result = []
subscriptions_ids = yield self.rc.smembers(TAG_SUBSCRIPTIONS_PREFIX.format(tag))
for sub_id in subscriptions_ids:
sub_json = yield self.rc.get(SUBSCRIPTION_PREFIX.format(sub_id))
if sub_json is not None:
sub = anyjson.loads(sub_json)
sub["id"] = sub_id
result.append(sub)
else:
yield self.rc.srem(TAG_SUBSCRIPTIONS_PREFIX.format(tag), sub_id)
defer.returnValue(result)
示例7: getTrigger
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def getTrigger(self, trigger_id):
"""
getTrigger(self, trigger_id)
- Read trigger by key {0}
- Unpack trigger json
:param tags: get with tags
:type tags: boolean
:param trigger_id: trigger identity
:type trigger_id: string
:rtype: tuple(json, trigger)
"""
pipeline = yield self.rc.pipeline()
pipeline.get(TRIGGER_PREFIX.format(trigger_id))
pipeline.smembers(TRIGGER_TAGS_PREFIX.format(trigger_id))
trigger = {}
json, trigger_tags = yield pipeline.execute_pipeline()
if json is not None:
trigger = anyjson.deserialize(json)
trigger = trigger_reformat(trigger, trigger_id, trigger_tags)
defer.returnValue((json, trigger))
示例8: _getTriggersChecks
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def _getTriggersChecks(self, triggers_ids):
triggers = []
pipeline = yield self.rc.pipeline()
for trigger_id in triggers_ids:
pipeline.get(TRIGGER_PREFIX.format(trigger_id))
pipeline.smembers(TRIGGER_TAGS_PREFIX.format(trigger_id))
pipeline.get(LAST_CHECK_PREFIX.format(trigger_id))
pipeline.get(TRIGGER_NEXT_PREFIX.format(trigger_id))
results = yield pipeline.execute_pipeline()
slices = [[triggers_ids[i / 4]] + results[i:i + 4] for i in range(0, len(results), 4)]
for trigger_id, trigger_json, trigger_tags, last_check, throttling in slices:
if trigger_json is None:
continue
trigger = anyjson.deserialize(trigger_json)
trigger = trigger_reformat(trigger, trigger_id, trigger_tags)
trigger["last_check"] = None if last_check is None else anyjson.deserialize(last_check)
trigger["throttling"] = long(throttling) if throttling and time.time() < long(throttling) else 0
triggers.append(trigger)
defer.returnValue(triggers)
示例9: getTriggersChecksPage
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def getTriggersChecksPage(self, start, size):
"""
getTriggersChecksPage(self, start, size)
- Returns triggers range from sorted set {0}
:param start: start position in range
:type start: integer
:param start: number of triggers
:type start: integer
:rtype: json
"""
pipeline = yield self.rc.pipeline()
pipeline.zrevrange(TRIGGERS_CHECKS, start=start, end=(start + size))
pipeline.zcard(TRIGGERS_CHECKS)
triggers_ids, total = yield pipeline.execute_pipeline()
triggers = yield self._getTriggersChecks(triggers_ids)
defer.returnValue((triggers, total))
示例10: getNotifications
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def getNotifications(self, start, end):
"""
getNotifications(self, start, end)
Read all planning notifications from sorted set {0}
:param start: range start
:type start: integer
:param end: range end
:type end: integer
"""
pipeline = yield self.rc.pipeline()
pipeline.zrange(NOTIFIER_NOTIFICATIONS, start=start, end=end)
pipeline.zcard(NOTIFIER_NOTIFICATIONS)
jsons, total = yield pipeline.execute_pipeline()
defer.returnValue((jsons, total))
示例11: removeNotification
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def removeNotification(self, id):
"""
removeNotification(self, id)
Remove planning notification by id string from sorted set {0}
:param id: notification id string
:type id: string
"""
notifications, total = yield self.getNotifications(0, -1)
for json in notifications:
notification = anyjson.loads(json)
timestamp = str(notification.get('timestamp'))
contact_id = notification.get('contact', {}).get('id')
sub_id = notification.get('event', {}).get('sub_id')
idstr = ''.join([timestamp, contact_id, sub_id])
if idstr == id:
result = yield self.rc.zrem(NOTIFIER_NOTIFICATIONS, json)
defer.returnValue(result)
示例12: getMetricsValues
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def getMetricsValues(self, metrics, startTime, endTime='+inf'):
"""
getMetricsValues(self, metrics, startTime, endTime)
Read multiple metric values from sorted set {0} from startTime
:param metrics: list of graphite metric path
:type metrics: list of string
:param startTime: unix epoch time
:type startTime: long
:param endTime: unix epoch time
:type endTime: long
:rtype: list of list of tuple ('value timestamp', long)
"""
pipeline = yield self.rc.pipeline()
for metric in metrics:
pipeline.zrangebyscore(METRIC_PREFIX.format(metric), min=startTime, max=endTime, withscores=True)
results = yield pipeline.execute_pipeline()
defer.returnValue(results)
示例13: cache
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def cache(f):
@wraps(f)
@defer.inlineCallbacks
def wrapper(*args, **kwargs):
if 'cache_key' in kwargs and 'cache_ttl' in kwargs:
key = "%s%s" % (f, kwargs['cache_key'])
ttl = kwargs['cache_ttl']
del kwargs['cache_key']
del kwargs['cache_ttl']
now = reactor.seconds()
@defer.inlineCallbacks
def get_value():
result = yield f(*args, **kwargs)
defer.returnValue(result)
timestamp, result = CACHE.get(key, (0, None))
if timestamp + ttl < now:
CACHE[key] = (now, result)
result = yield get_value()
CACHE[key] = (now, result)
else:
result = yield f(*args, **kwargs)
defer.returnValue(result)
return wrapper
示例14: get_timeseries
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def get_timeseries(self, requestContext):
targets = self.struct.get("targets", [])
target_time_series = TargetTimeSeries()
target_number = 1
for target in targets:
time_series = yield evaluateTarget(requestContext, target)
if target_number > 1:
if len(time_series) == 1:
target_time_series.other_targets_names["t%s" % target_number] = time_series[0].name
elif not time_series:
raise Exception("Target #%s has no timeseries" % target_number)
else:
raise Exception("Target #%s has more than one timeseries" % target_number)
for time_serie in time_series:
time_serie.last_state = self.last_check["metrics"].get(
time_serie.name, {
"state": state.NODATA,
"timestamp": time_serie.start - 3600})
target_time_series[target_number] = time_series
target_number += 1
defer.returnValue(target_time_series)
示例15: test_retry_with_twisted
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import returnValue [as 别名]
def test_retry_with_twisted(mock_client, mock_response):
from twisted.internet import defer
@defer.inlineCallbacks
def return_response():
yield
defer.returnValue(mock_response)
# Setup
mock_response.with_json({"id": 123, "name": "prkumar"})
mock_client.with_side_effect([Exception, return_response()])
mock_client.with_io(io.TwistedStrategy())
github = GitHub(base_url=BASE_URL, client=mock_client)
# Run
response = yield github.get_user("prkumar")
assert len(mock_client.history) == 2
assert response.json() == {"id": 123, "name": "prkumar"}