本文整理汇总了Python中tornado.locks.Condition.notify方法的典型用法代码示例。如果您正苦于以下问题:Python Condition.notify方法的具体用法?Python Condition.notify怎么用?Python Condition.notify使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.locks.Condition
的用法示例。
在下文中一共展示了Condition.notify方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_data
# 需要导入模块: from tornado.locks import Condition [as 别名]
# 或者: from tornado.locks.Condition import notify [as 别名]
def get_data(cls, account, source_filter, limit=100, skip=0):
"""
Gathers card information from Google Sheets
GET https://spreadsheets.google.com/feeds/list/[spreadsheet]/[worksheet]/private/full
"""
if not account or not account.enabled:
raise ValueError('cannot gather information without an account')
client = AsyncHTTPClient()
if source_filter.spreadsheet is None:
raise ValueError('required parameter spreadsheet missing')
if source_filter.worksheet is None:
raise ValueError('required parameter worksheet missing')
uri = "https://docs.google.com/spreadsheets/d/{}/export?format=csv&gid={}".format(
source_filter.spreadsheet, source_filter.worksheet
)
app_log.info(
"Start retrieval of worksheet {}/{} for {}".format(source_filter.spreadsheet, source_filter.worksheet,
account._id))
lock = Condition()
oauth_client = account.get_client()
uri, headers, body = oauth_client.add_token(uri)
req = HTTPRequest(uri, headers=headers, body=body, streaming_callback=lambda c: cls.write(c))
client.fetch(req, callback=lambda r: lock.notify())
yield lock.wait(timeout=timedelta(seconds=MAXIMUM_REQ_TIME))
app_log.info(
"Finished retrieving worksheet for {}".format(account._id))
示例2: PingHandler
# 需要导入模块: from tornado.locks import Condition [as 别名]
# 或者: from tornado.locks.Condition import notify [as 别名]
class PingHandler(firenado.tornadoweb.TornadoHandler):
def __init__(self, application, request, **kwargs):
super(PingHandler, self).__init__(application, request, **kwargs)
self.callback_queue = None
self.condition = Condition()
self.response = None
self.corr_id = str(uuid.uuid4())
self.in_channel = self.application.get_app_component().rabbitmq[
'client'].channels['in']
@gen.coroutine
def post(self):
self.in_channel.queue_declare(exclusive=True,
callback=self.on_request_queue_declared)
yield self.condition.wait()
self.write(self.response)
def on_request_queue_declared(self, response):
logger.info('Request temporary queue declared.')
self.callback_queue = response.method.queue
self.in_channel.basic_consume(self.on_response, no_ack=True,
queue=self.callback_queue)
self.in_channel.basic_publish(
exchange='',
routing_key='ping_rpc_queue',
properties=pika.BasicProperties(
reply_to=self.callback_queue,
correlation_id=self.corr_id,
),
body=self.request.body)
def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id:
self.response = {
'data': body.decode("utf-8"),
'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
self.in_channel.queue_delete(queue=self.callback_queue)
self.condition.notify()
示例3: InMemStream
# 需要导入模块: from tornado.locks import Condition [as 别名]
# 或者: from tornado.locks.Condition import notify [as 别名]
class InMemStream(Stream):
def __init__(self, buf=None, auto_close=True):
"""In-Memory based stream
:param buf: the buffer for the in memory stream
"""
self._stream = deque()
if buf:
self._stream.append(buf)
self.state = StreamState.init
self._condition = Condition()
self.auto_close = auto_close
self.exception = None
def clone(self):
new_stream = InMemStream()
new_stream.state = self.state
new_stream.auto_close = self.auto_close
new_stream._stream = deque(self._stream)
return new_stream
def read(self):
def read_chunk(future):
if self.exception:
future.set_exception(self.exception)
return future
chunk = ""
while len(self._stream) and len(chunk) < common.MAX_PAYLOAD_SIZE:
chunk += self._stream.popleft()
future.set_result(chunk)
return future
read_future = tornado.concurrent.Future()
# We're not ready yet
if self.state != StreamState.completed and not len(self._stream):
wait_future = self._condition.wait()
wait_future.add_done_callback(
lambda f: f.exception() or read_chunk(read_future)
)
return read_future
return read_chunk(read_future)
def write(self, chunk):
if self.exception:
raise self.exception
if self.state == StreamState.completed:
raise UnexpectedError("Stream has been closed.")
if chunk:
self._stream.append(chunk)
self._condition.notify()
# This needs to return a future to match the async interface.
r = tornado.concurrent.Future()
r.set_result(None)
return r
def set_exception(self, exception):
self.exception = exception
self.close()
def close(self):
self.state = StreamState.completed
self._condition.notify()
示例4: DeviceConnection
# 需要导入模块: from tornado.locks import Condition [as 别名]
# 或者: from tornado.locks.Condition import notify [as 别名]
class DeviceConnection(object):
state_waiters = {}
state_happened = {}
def __init__ (self, device_server, stream, address):
self.fw_version = 0.0
self.recv_msg_cond = Condition()
self.recv_msg = {}
self.send_msg_sem = Semaphore(1)
self.pending_request_cnt = 0
self.device_server = device_server
self.stream = stream
self.address = address
self.stream.set_nodelay(True)
self.timeout_handler_onlinecheck = None
self.timeout_handler_offline = None
self.killed = False
self.sn = ""
self.private_key = ""
self.node_id = 0
self.iv = None
self.cipher_down = None
self.cipher_up = None
#self.state_waiters = []
#self.state_happened = []
self.event_waiters = []
self.event_happened = []
self.ota_ing = False
self.ota_notify_done_future = None
self.post_ota = False
self.online_status = True
@gen.coroutine
def secure_write (self, data):
if self.cipher_down:
cipher_text = self.cipher_down.encrypt(pad(data))
yield self.stream.write(cipher_text)
@gen.coroutine
def wait_hello (self):
try:
self._wait_hello_future = self.stream.read_bytes(64) #read 64bytes: 32bytes SN + 32bytes signature signed with private key
str1 = yield gen.with_timeout(timedelta(seconds=10), self._wait_hello_future,
io_loop=ioloop.IOLoop.current())
self.idle_time = 0 #reset the idle time counter
if len(str1) != 64:
self.stream.write("sorry\r\n")
yield gen.sleep(0.1)
self.kill_myself()
gen_log.debug("receive length != 64")
raise gen.Return(100) # length not match 64
if re.match(r'@\d\.\d', str1[0:4]):
#new version firmware
self._wait_hello_future = self.stream.read_bytes(4) #read another 4bytes
str2 = yield gen.with_timeout(timedelta(seconds=10), self._wait_hello_future, io_loop=ioloop.IOLoop.current())
self.idle_time = 0 #reset the idle time counter
if len(str2) != 4:
self.stream.write("sorry\r\n")
yield gen.sleep(0.1)
self.kill_myself()
gen_log.debug("receive length != 68")
raise gen.Return(100) # length not match 64
str1 += str2
self.fw_version = float(str1[1:4])
sn = str1[4:36]
sig = str1[36:68]
else:
#for version < 1.1
sn = str1[0:32]
sig = str1[32:64]
gen_log.info("accepted sn: %s @fw_version %.1f" % (sn, self.fw_version))
#query the sn from database
node = None
cur = self.device_server.cur
cur.execute('select * from nodes where node_sn="%s"'%sn)
rows = cur.fetchall()
if len(rows) > 0:
node = rows[0]
if not node:
self.stream.write("sorry\r\n")
yield gen.sleep(0.1)
self.kill_myself()
gen_log.info("node sn not found")
raise gen.Return(101) #node not found
key = node['private_key']
key = key.encode("ascii")
#.........这里部分代码省略.........
示例5: DeviceConnection
# 需要导入模块: from tornado.locks import Condition [as 别名]
# 或者: from tornado.locks.Condition import notify [as 别名]
class DeviceConnection(object):
state_waiters = {}
state_happened = {}
def __init__ (self, device_server, stream, address):
self.recv_msg_cond = Condition()
self.recv_msg = {}
self.send_msg_sem = Semaphore(1)
self.pending_request_cnt = 0
self.device_server = device_server
self.stream = stream
self.address = address
self.stream.set_nodelay(True)
self.idle_time = 0;
self.killed = False
self.sn = ""
self.private_key = ""
self.node_id = 0
self.name = ""
self.iv = None
self.cipher = None
#self.state_waiters = []
#self.state_happened = []
self.event_waiters = []
self.event_happened = []
self.ota_ing = False
self.ota_notify_done_future = None
self.post_ota = False
self.online_status = True
@gen.coroutine
def secure_write (self, data):
if self.cipher:
cipher_text = self.cipher.encrypt(pad(data))
yield self.stream.write(cipher_text)
@gen.coroutine
def wait_hello (self):
try:
self._wait_hello_future = self.stream.read_bytes(64) #read 64bytes: 32bytes SN + 32bytes signature signed with private key
str = yield gen.with_timeout(timedelta(seconds=10), self._wait_hello_future, io_loop=self.stream.io_loop)
self.idle_time = 0 #reset the idle time counter
if len(str) != 64:
self.stream.write("sorry\r\n")
yield gen.sleep(0.1)
self.kill_myself()
gen_log.debug("receive length != 64")
raise gen.Return(100) # length not match 64
sn = str[0:32]
sig = str[32:64]
gen_log.info("accepted sn: "+ sn)
#query the sn from database
node = None
for n in NODES_DATABASE:
if n['node_sn'] == sn:
node = n
break
if not node:
self.stream.write("sorry\r\n")
yield gen.sleep(0.1)
self.kill_myself()
gen_log.info("node sn not found")
raise gen.Return(101) #node not found
key = node['node_key']
key = key.encode("ascii")
sig0 = hmac.new(key, msg=sn, digestmod=hashlib.sha256).digest()
gen_log.debug("sig: "+ binascii.hexlify(sig))
gen_log.debug("sig calc:"+ binascii.hexlify(sig0))
if sig0 == sig:
#send IV + AES Key
self.sn = sn
self.private_key = key
self.node_id = node['node_sn']
self.name = node['name']
gen_log.info("valid hello packet from node %s" % self.name)
#remove the junk connection of the same sn
self.stream.io_loop.add_callback(self.device_server.remove_junk_connection, self)
#init aes
self.iv = Random.new().read(AES.block_size)
self.cipher = AES.new(key, AES.MODE_CFB, self.iv, segment_size=128)
cipher_text = self.iv + self.cipher.encrypt(pad("hello"))
gen_log.debug("cipher text: "+ cipher_text.encode('hex'))
self.stream.write(cipher_text)
raise gen.Return(0)
else:
self.stream.write("sorry\r\n")
yield gen.sleep(0.1)
self.kill_myself()
#.........这里部分代码省略.........