使用协程实现调用接口 验证抽奖概率

原文地址

在原先的基础上使用协程进行改进,提高效率

  • fetch 函数:用于发送请求并返回响应文本。
    delay 用于指定延迟时间
python 复制代码
async def fetch(session, url, headers, payload, delay=0):
    await asyncio.sleep(delay)
    async with session.post(url, headers=headers, data=payload, ssl=False) as response:
        return await response.text()
  • main 函数:创建一个 aiohttp.ClientSession 会话,并启动多个并发的 fetch 任务。asyncio.gather 用于等待所有任务完成,并收集它们的结果。
python 复制代码
async def main(url, headers, payload, n, delay):
    d = defaultdict(int)
    lock = asyncio.Lock()  # 创建锁

    async with aiohttp.ClientSession() as session:
        tasks = [fetch_and_update(session, url, headers, payload, d, lock, delay) for _ in range(n)]
        await asyncio.gather(*tasks)

    return d
  • 任务列表:tasks 列表包含了 n 个 fetch 任务。
  • 解析响应:所有响应返回后,逐个解析 JSON 数据并更新结果字典 d。
  • 运行主协程:使用 asyncio.get_event_loop() 和 loop.run_until_complete(main(...)) 启动和运行主协程,获取最终结果。
python 复制代码
if __name__ == '__main__':
	url = ''
	headers = ''
	payload = ''
	n = 100000
	delay = 0.1 # 单位是s
	loop = asyncio.get_event_loop()
	result = loop.run_until_complete(main(url, headers, payload, n, delay))
	get_lottery(result)
	

加锁

由于是对同一个字典进行操作,需要保证操作的线程安全性,保证数据一致性,需要加锁处理 ,使用asyncio.Lock

python 复制代码
async def fetch_and_update(session, url, headers, payload, d, lock, delay):
    response = await fetch(session, url, headers, payload, delay)
    jsonobj = json.loads(response)
    reward_name = jsonobj['']

    async with lock:  # 确保对字典的访问是线程安全的
        d[reward_name] += 1


def get_lottery(d):
    for key, value in d.items():
        lottery = value / n
        print(key + "的概率是:" + '{:.2%}'.format(lottery))
相关推荐
阿尔的代码屋5 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django