美文网首页
并发编程async await

并发编程async await

作者: 千沙qiansha | 来源:发表于2020-12-02 13:50 被阅读0次

多次请求地址获取返回值

async def refresh_switch_update_rate(ip,switch_id):

    try:
        print('交换机%s端口正在刷新' % ip)
        url = 'http://localhost:8080/api/v1/query?query=avg by (ifDescr)(ifHighSpeed{instance="%s"})/10' % str(ip)
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                res = await response.text()
                status = json.loads(res).get('status')
                result = json.loads(res).get('data').get('result')
                if status == 'success':
                    print("requests请求连接成功")
                    port_list = [(port_items.get('metric').get('ifDescr'),port_items.get('value')[1]) for port_items in
                                 result]
                    SwitchPort.objects.bulk_create(SwitchPort(name=name, switch_id=switch_id,update_rate=update_rate + 'Mbit/s') for name,update_rate in port_list)
                    print('交换机%s端口刷新完成' % ip)
                return '交换机%s端口刷新完成' % ip
    except Exception as e:
        print(e)
        return

def refresh_run():
    ip_list = Switch.objects.all().values_list('ip', 'id')
    loop = asyncio.get_event_loop()
    tasks = [asyncio.ensure_future(refresh_switch_update_rate(ip,swich_id)) for ip,swich_id in ip_list]
    res = loop.run_until_complete(asyncio.gather(*tasks))
    print(res)

POST请求时,数据中包含对象【字典或者列表】时,需要json,否则会直接将对象标为字符串。

async def refresh_portmonitor(data):
    headers = {'Authorization': Dev.token}
    try:
        url = Dev.url
        async with aiohttp.ClientSession(headers=headers) as session:
            async with session.post(url, json=data) as response:
                return response

    except Exception as e:
        print(e)
        return

相关文章

网友评论

      本文标题:并发编程async await

      本文链接:https://www.haomeiwen.com/subject/cxoywktx.html