test2--start: 1652973708 work start work work end work test2--end: 1652973716 test1--执行 INFO: 127.0.0.1:63965 - "GET /test/test2 HTTP/1.1" 200 OK INFO: 127.0.0.1:63966 - "GET /test/test1 HTTP/1.1" 200 OK
@api.get("/test2") deftest2(): a = int(time.time()) print(f"test2--start: {a}") work(8) b = int(time.time()) print(f"test2--end: {b}") returnf"test2耗时:{b-a}"
此时运行测试脚本,执行顺序如下
1 2 3 4 5 6 7
test1--执行 test2--start: 1652973918 work start work INFO: 127.0.0.1:64024 - "GET /test/test1 HTTP/1.1" 200 OK work end work test2--end: 1652973926 INFO: 127.0.0.1:64023 - "GET /test/test2 HTTP/1.1" 200 OK
@api.get("/test2") asyncdeftest2(): a = int(time.time()) print(f"test2--start: {a}") loop = asyncio.get_event_loop() await loop.run_in_executor(None, work, 8) b = int(time.time()) print(f"test2--end: {b}") returnf"test2耗时:{b-a}"
执行顺序如下
1 2 3 4 5 6 7
test2--start: 1652974163 work start work test1--执行 INFO: 127.0.0.1:64094 - "GET /test/test1 HTTP/1.1" 200 OK work end work test2--end: 1652974171 INFO: 127.0.0.1:64093 - "GET /test/test2 HTTP/1.1" 200 OK