0
我正在查看python3 asyncio,它看起來很棒,因爲我來自gevent。但是,我仍然試圖找出如何做到一切。比方說,我試圖做一個簡單的服務,連接到一個redis隊列並從中彈出項目。事情變得非常快速:當對象被銷燬時,我需要一個上下文管理器來關閉redis連接,我需要一個異步redis驅動程序,並且我需要捕獲SIGINT和SIGTERM信號。從python2轉到python3 asyncio gevent
import asyncio
import asyncio_redis
class Agent(object):
def __init__(self, name):
print("hello, i'm %s" % name)
self.name = name
self.running = True
# self.redis should become an instance of asyncio_redis.Connection
def shutdown(self):
self.running = False
def __enter__(self):
return self
def __exit__(self):
print("%s cleaned up" % name)
self.redis.close()
def loop(self):
print("%s started looping" % name)
while self.running:
# msg should get a value from self.redis.brpop(["queue"], 10)
if msg:
print "%s recv %s" % (name, msg)
else:
pass
if __name__ == "__main__":
loop = asyncio.get_event_loop()
try:
with a as Agent("agent1"):
loop.add_signal_handler(signal.SIGINT, a.shutdown)
loop.run_until_complete(a.loop())
finally:
loop.stop()
loop.close()
任何人都可以完成代碼並使其運行?謝謝。