是否可以与Python异步发送许多请求

时间:2017-10-27 15:59:16

标签: python django http asynchronous slack-api

我正在尝试发送大约70个松弛api的请求,但找不到以异步方式实现它的方法,我有大约3秒钟或者我得到timeout error

这里我是如何尝试实现它的:

import asyncio

def send_msg_to_all(sc,request,msg):
    user_list = sc.api_call(
       "users.list"
    )
members_array = user_list["members"]

ids_array = []
for member in members_array:
    ids_array.append(member['id'])
real_users = []

for user_id in ids_array:

    user_channel = sc.api_call(
        "im.open",
        user=user_id,
    )
    if user_channel['ok'] == True:
        real_users.append(User(user_id, user_channel['channel']['id']) )

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(send_msg(sc, real_users, request, msg))
loop.close()
return HttpResponse()


async def send_msg(sc, real_users, req, msg):
    for user in real_users:    
        send_ephemeral_msg(sc,user.user_id,user.dm_channel, msg)


def send_ephemeral_msg(sc, user, channel, text):
    sc.api_call(
        "chat.postEphemeral",
        channel=channel,
        user=user,
        text=text
    )  

但看起来我仍然以同步方式进行此操作

任何想法的家伙?

1 个答案:

答案 0 :(得分:0)

Slack的API的速率限制为每秒1次查询(QPS)documented here

即使你正常工作,你也会超出限制,你会开始看到HTTP 429 Too Many Requests错误。如果继续以该速率继续,您的API令牌甚至可能会被撤销/取消。

我认为你需要找到一种不同的方式。