I'm trying to write a small parallel thread handler using the Slack RTM API, and I wonder how much this is the most efficient use of Python coroutines. The package asynciohas a lot of options, but it is difficult to determine what is the right approach for the project, and the documentation, I think, does not explain very well what advantages / disadvantages are for everyone.
I think that I do not need to have the overhead of multiple threads here, and I need the connection between asynchronous loops. Should I create a separate one BaseEventLoopfor each of my functions?
Being Python, I think there is an almost deterministic answer to this question ( There should be one-- and preferably only one --obvious way to do it), but I'm afraid that adding all this asynchronous Cruft might just make my code less productive than a fully consistent naive implementation.
incoming_message_q = asyncio.Queue()
async def print_event():
logging.info("Entering log loop")
while True:
event = await incoming_message_q.get()
logging.info(event)
async def log_queue_status():
while True:
logging.info(incoming_message_q.qsize())
await asyncio.sleep(5)
async def read_rtm_connection(client, q):
if client.rtm_connect():
logging.info("Successful Slack RTM connection")
while True:
events = client.rtm_read()
for event in events:
logging.info("Putting onto the queue", event)
if event["type"] == "presence_change":
await q.put(event)
elif event["type"] == "message":
await q.put(event)
else:
logging.info("Not sure what to do")
await asyncio.sleep(0.1)
else:
logging.info("RTM connection failed.")
loop = asyncio.get_event_loop()
loop.create_task(print_event())
loop.create_task(log_queue_status())
loop.create_task(read_rtm_connection(client, incoming_message_q))
loop.run_forever()
source
share