本文整理汇总了Python中twisted.internet.reactor.seconds方法的典型用法代码示例。如果您正苦于以下问题:Python reactor.seconds方法的具体用法?Python reactor.seconds怎么用?Python reactor.seconds使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.reactor
的用法示例。
在下文中一共展示了reactor.seconds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cache
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [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
示例2: messageReceived
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def messageReceived(self, ignored, channel, message, nocache=False):
try:
json = anyjson.deserialize(message)
db = self.factory.db
db.last_data = reactor.seconds()
pattern = json["pattern"]
metric = json["metric"]
yield db.addPatternMetric(pattern, metric)
triggers = yield db.getPatternTriggers(pattern)
if not triggers:
yield db.removePattern(pattern)
metrics = yield db.getPatternMetrics(pattern)
for metric in metrics:
yield db.delMetric(metric)
yield db.delPatternMetrics(pattern)
for trigger_id in triggers:
if nocache:
yield db.addTriggerCheck(trigger_id)
else:
yield db.addTriggerCheck(trigger_id, cache_key=trigger_id, cache_ttl=config.CHECK_INTERVAL)
except Exception as e:
log.error("Failed to receive metric: {e}", e=e)
示例3: perform
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def perform(self):
try:
trigger_id = yield self.db.getTriggerToCheck()
while trigger_id is not None:
acquired = yield self.db.setTriggerCheckLock(trigger_id)
if acquired is not None:
start = reactor.seconds()
trigger = Trigger(trigger_id, self.db)
yield trigger.check()
end = reactor.seconds()
yield self.db.delTriggerCheckLock(trigger_id)
spy.TRIGGER_CHECK.report(end - start)
trigger_id = yield self.db.getTriggerToCheck()
yield task.deferLater(reactor, random.uniform(PERFORM_INTERVAL * 10, PERFORM_INTERVAL * 20), lambda: None)
except GeneratorExit:
pass
except Exception as e:
spy.TRIGGER_CHECK_ERRORS.report(0)
log.error("Failed to perform triggers check: {e}", e=e)
yield task.deferLater(reactor, ERROR_TIMEOUT, lambda: None)
示例4: test_startCheckingExpiration
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def test_startCheckingExpiration(self):
"""
L{server.Session.startCheckingExpiration} causes the session to expire
after L{server.Session.sessionTimeout} seconds without activity.
"""
self.session.startCheckingExpiration()
# Advance to almost the timeout - nothing should happen.
self.clock.advance(self.session.sessionTimeout - 1)
self.assertIn(self.uid, self.site.sessions)
# Advance to the timeout, the session should expire.
self.clock.advance(1)
self.assertNotIn(self.uid, self.site.sessions)
# There should be no calls left over, either.
self.assertFalse(self.clock.calls)
示例5: test_nonASCII
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def test_nonASCII(self):
"""
Bytes in fields of the request which are not part of ASCII are escaped
in the result.
"""
reactor = Clock()
reactor.advance(1234567890)
timestamp = http.datetimeToLogString(reactor.seconds())
request = DummyRequestForLogTest(http.HTTPFactory(reactor=reactor))
request.client = IPv4Address("TCP", b"evil x-forwarded-for \x80", 12345)
request.method = b"POS\x81"
request.protocol = b"HTTP/1.\x82"
request.requestHeaders.addRawHeader(b"referer", b"evil \x83")
request.requestHeaders.addRawHeader(b"user-agent", b"evil \x84")
line = http.combinedLogFormatter(timestamp, request)
self.assertEqual(
u'"evil x-forwarded-for \\x80" - - [13/Feb/2009:23:31:30 +0000] '
u'"POS\\x81 /dummy HTTP/1.0" 123 - "evil \\x83" "evil \\x84"',
line)
示例6: _xforwardedforTest
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def _xforwardedforTest(self, header):
"""
Assert that a request with the given value in its I{X-Forwarded-For}
header is logged by L{proxiedLogFormatter} the same way it would have
been logged by L{combinedLogFormatter} but with 172.16.1.2 as the
client address instead of the normal value.
@param header: An I{X-Forwarded-For} header with left-most address of
172.16.1.2.
"""
reactor = Clock()
reactor.advance(1234567890)
timestamp = http.datetimeToLogString(reactor.seconds())
request = DummyRequestForLogTest(http.HTTPFactory(reactor=reactor))
expected = http.combinedLogFormatter(timestamp, request).replace(
u"1.2.3.4", u"172.16.1.2")
request.requestHeaders.setRawHeaders(b"x-forwarded-for", [header])
line = http.proxiedLogFormatter(timestamp, request)
self.assertEqual(expected, line)
示例7: test_seconds
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def test_seconds(self):
"""
L{twisted.internet.reactor.seconds} should return something
like a number.
1. This test specifically does not assert any relation to the
"system time" as returned by L{time.time} or
L{twisted.python.runtime.seconds}, because at some point we
may find a better option for scheduling calls than
wallclock-time.
2. This test *also* does not assert anything about the type of
the result, because operations may not return ints or
floats: For example, datetime-datetime == timedelta(0).
"""
now = reactor.seconds()
self.assertEqual(now-now+now, now)
示例8: advanceCompletely
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def advanceCompletely(self, amount):
"""
Move time on this clock forward by the given amount and run whatever
pending calls should be run. Always complete the deferred calls before
returning.
@type amount: C{float}
@param amount: The number of seconds which to advance this clock's
time.
"""
self.rightNow += amount
self._sortCalls()
while self.calls and self.calls[0].getTime() <= self.seconds():
call = self.calls.pop(0)
call.called = 1
yield call.func(*call.args, **call.kw)
self._sortCalls()
示例9: test_clientAddrIPv6
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def test_clientAddrIPv6(self):
"""
A request from an IPv6 client is logged with that IP address.
"""
reactor = Clock()
reactor.advance(1234567890)
timestamp = http.datetimeToLogString(reactor.seconds())
request = DummyRequestForLogTest(http.HTTPFactory(reactor=reactor))
request.client = IPv6Address("TCP", b"::1", 12345)
line = http.combinedLogFormatter(timestamp, request)
self.assertEqual(
u'"::1" - - [13/Feb/2009:23:31:30 +0000] '
u'"GET /dummy HTTP/1.0" 123 - "-" "-"',
line)
示例10: test_clientAddrUnknown
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def test_clientAddrUnknown(self):
"""
A request made from an unknown address type is logged as C{"-"}.
"""
@implementer(interfaces.IAddress)
class UnknowableAddress(object):
"""
An L{IAddress} which L{combinedLogFormatter} cannot have
foreknowledge of.
"""
reactor = Clock()
reactor.advance(1234567890)
timestamp = http.datetimeToLogString(reactor.seconds())
request = DummyRequestForLogTest(http.HTTPFactory(reactor=reactor))
request.client = UnknowableAddress()
line = http.combinedLogFormatter(timestamp, request)
self.assertTrue(line.startswith(u'"-" '))
示例11: start
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def start(self):
msg = bytearray('\0' * self.size)
i = [0]
def _sendmsg(c):
if c > 1:
log.msg('Packet source freeze for %d intervals at iter %d' % (c, i[0]))
struct.pack_into('!HId', msg, 0, self.size, i[0], reactor.seconds())
self.transport.write(msg, self.addr)
i[0] += 1
if i[0] >= self.count:
lc.stop()
lc = task.LoopingCall.withCount(_sendmsg)
return lc.start(1.0 / self.rate, now=False)
示例12: test_seconds
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def test_seconds(self):
"""
L{twisted.internet.reactor.seconds} should return something
like a number.
1. This test specifically does not assert any relation to the
"system time" as returned by L{time.time} or
L{twisted.python.runtime.seconds}, because at some point we
may find a better option for scheduling calls than
wallclock-time.
2. This test *also* does not assert anything about the type of
the result, because operations may not return ints or
floats: For example, datetime-datetime == timedelta(0).
"""
now = reactor.seconds()
self.assertEquals(now-now+now, now)
示例13: add_ban
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def add_ban(self, ip, reason, duration, name=None):
"""
Ban an ip with an optional reason and duration in seconds. If duration
is None, ban is permanent.
"""
network = ip_network(str(ip), strict=False)
for connection in list(self.connections.values()):
if ip_address(connection.address[0]) in network:
name = connection.name
connection.kick(silent=True)
if duration:
duration = time.time() + duration
else:
duration = None
self.bans[ip] = (name or '(unknown)', reason, duration)
self.save_bans()
示例14: data_received
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def data_received(self, peer: Peer, packet: Packet) -> None:
ip = peer.address.host
current_time = reactor.seconds()
try:
ServerProtocol.data_received(self, peer, packet)
except (NoDataLeft, ValueError):
import traceback
traceback.print_exc()
log.info(
'IP %s was hardbanned for invalid data or possibly DDoS.' % ip)
self.hard_bans.add(ip)
return
dt = reactor.seconds() - current_time
if dt > 1.0:
log.warn('processing {!r} from {} took {}'.format(
packet.data, ip, dt))
示例15: update_world
# 需要导入模块: from twisted.internet import reactor [as 别名]
# 或者: from twisted.internet.reactor import seconds [as 别名]
def update_world(self):
last_time = self.last_time
current_time = reactor.seconds()
if last_time is not None:
dt = current_time - last_time
if dt > 1.0:
log.warn('high CPU usage detected - %s' % dt)
self.last_time = current_time
ServerProtocol.update_world(self)
time_taken = reactor.seconds() - current_time
if time_taken > 1.0:
log.warn(
'World update iteration took %s, objects: %s' %
(time_taken, self.world.objects))
# events