在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python  網(wǎng)絡(luò)安全/ 請(qǐng)問這樣的模型,用異步aysncio怎么寫呢?

請(qǐng)問這樣的模型,用異步aysncio怎么寫呢?

a函數(shù)請(qǐng)求api,b函數(shù)請(qǐng)求api,a和b函數(shù)盡量同時(shí)發(fā)出請(qǐng)求。
a 和 b返回的結(jié)果扔給c函數(shù)去處理寫入數(shù)據(jù)庫(kù)!
a和b函數(shù)把結(jié)果給c的時(shí)候,馬上又開始執(zhí)行api請(qǐng)求!

這樣的異步用asyncio要怎么寫呢?

回答
編輯回答
初念
import time
import asyncio
from multiprocessing import Process, Queue
from concurrent.futures import ThreadPoolExecutor

async def api_a():
    await asyncio.sleep(2)
    return str(time.time())

async def api_b():
    await asyncio.sleep(3)
    return str(time.time())

class Test(object):
    def __init__(self):
        self._a = ''
        self._b = ''
        
    async def a(self):
        self._a = await api_a()
        
    async def b(self):
        self._b = await api_b()
def each_op(s):
    time.sleep(5)
    print('do some operation')
    print(s)
        
def db_op(q):
    start = time.time()
    with ThreadPoolExecutor(5) as executor:
        while 1:
            if not q.empty():
                s = q.get(True)
                if s is None:
                    print('no more api task')
                    break
                executor.submit(each_op, s)
    print('no more db task')        
    print('db time:', time.time()-start)
if __name__ == '__main__':
    start = time.time()
    t = Test()
    q = Queue()
    op = Process(target=db_op, args=(q,))
    op.start()
    loop = asyncio.get_event_loop()
    for _ in range(5):
        loop.run_until_complete(asyncio.wait([t.a(), t.b()]))
        q.put((t._a, t._b))
    loop.close()    
    q.put(None)
    print('api time:', time.time() - start)     

終端調(diào)用:

python3 test.py

結(jié)果:

do some operation
('1517222152.4486094', '1517222153.4516666')
do some operation
('1517222155.451781', '1517222156.4548383')
do some operation
('1517222158.4549527', '1517222159.4580102')
api time: 15.032859802246094
no more api task
do some operation
('1517222161.4581246', '1517222162.4611819')
do some operation
('1517222164.4612963', '1517222165.4643538')
no more db task
db time: 19.849135398864746
2017年3月5日 22:39