框架sanic學習之如何解決介面內部有多個耗時邏輯非同步執行
阿新 • • 發佈:2021-12-22
程式碼見成果
人生苦短,我用python!#!/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()