框架sanic学习之如何解决接口内部有多个耗时逻辑异步执行
代码见成果
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:SunXiuWen
# datetime:2021/12/22 0022
"""查询订单详情
难点:详情的需要的订单历史状态信息、发票信息、订单基础信息,分销信息等都不在同一个表里
一个个查非常耗时
"""
import time
import asyncio
from sanic import Sanic
from sanic import response
app = Sanic(name="MyOder")
async def query_order_info(order_id):
await asyncio.sleep(5)
return dict(order_info=order_id)
async def query_order_history(order_id):
await asyncio.sleep(10)
return dict(order_history=order_id)
@app.get('/v1/api/order/detail')
async def get_order_detail(request):
begin = time.time()
code, desc, data = 200, "success", {}
order_id = request.args.get("order_id")
my_loop = request.app.loop
task1 = my_loop.create_task(query_order_info(order_id))
task2 = my_loop.create_task(query_order_history(order_id))
sort_result_list = await asyncio.gather(task1, task2)
for i in sort_result_list:
data.update(i)
return response.json(body=dict(code=code, desc=desc, data=data, request_total_time=time.time() - begin))
if __name__ == '__main__':
app.run()
人生苦短,我用python!