Python 異步HTTP

async def post_httpresp(param):
    with async_timeout.timeout(1.0):
        async with aiohttp.ClientSession() as session:
            try:
                async with session.post(searchurl, json=param) as resposne:
                    res = await resposne.read()
                    if eval(res)['status'] == 200:
                        print(eval(res))
                    else:
                        print("過程異常")
            except:
                print('timeout', param)
                await session.close()

 

async def get_httpresp(url, val): 
    with async_timeout.timeout(1.0):
        async with aiohttp.ClientSession() as session:
            try:
                async with session.get(url) as resposne:
                    res = await resposne.text()
                    if eval(res).get("status", 0) == 200:
                        pass
            except:
                 print('timeout', url)
                 await session.close()

 

創建session會浪費資源,所以在實際應用中把創建session 移到外面,向函數內傳遞session對象即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章