zoukankan      html  css  js  c++  java
  • python36异步任务 获取ip地址的地理位置

    # encoding: utf-8
    
    import asyncio
    import requests
    import functools
    
    url = "http://ip.zxinc.org/api.php"
    
    params_list = []  # 存放所有要查询的参数
    with open("IPv6.txt", 'r', encoding='utf-8') as f:
        for ip in f:
            ip = ip.strip()
            payload = {"type": "json", "ip": ip}
            params_list.append(payload)
    
    
    def save_result(res):  # task回调函数
        print(res)
        params, response = res.result()  # 这就是get_ip_location函数的返回值,通过异步任务的result函数获取
    
        if response.status_code == 500:
            with open("save_result22.txt", "a+", encoding="utf-8") as f1:
                f1.write(params["ip"] + " = 地址有误" + "
    ")
        else:
            result = response.json()
            country = result["data"]["country"]
            with open("save_result22.txt", "a+", encoding="utf-8") as f1:
                f1.write(params["ip"] + " = " + country + "
    ")
    
    
    async def get_ip_location(param):  # 发送get请求
        print("start ", param)
        # param = {"type": "json", "ip": "1.1.1.1"}  param是requests.get的参数
        loop = asyncio.get_event_loop()
        try:
            # 要使用await, 必须将第三方包转为awaitable对象
            response = await loop.run_in_executor(None, functools.partial(requests.get, url=url, params=param))
            return param, response
        except Exception as e:
            return param, e
    
    tasks = []
    for param in params_list:
        task = asyncio.ensure_future(get_ip_location(param))  # 1.创建异步任务
        task.add_done_callback(save_result)  # 2.给任务添加回调函数
        tasks.append(task)
    loop = asyncio.get_event_loop()  # 3.创建事件循环
    loop.run_until_complete(asyncio.wait(tasks))  # 4.执行所有异步任务
  • 相关阅读:
    python 学习 3-1 (编码)
    mongdb备份
    docker 部署redis , mongodb ,rabbitmq
    python学习第一天第二天总结
    python 学习 (1-3)
    python学习(day1-2)
    Activiti工作流搭建教程
    docker Compose安装
    CAS 单点登录(代码部分)
    推送自定义docker镜像到阿里云
  • 原文地址:https://www.cnblogs.com/wt11/p/9927839.html
Copyright © 2011-2022 走看看