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"] + " = 地址有误" + "\n")
    else:
        result = response.json()
        country = result["data"]["country"]
        with open("save_result22.txt", "a+", encoding="utf-8") as f1:
            f1.write(params["ip"] + " = " + country + "\n")


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.执行所有异步任务

 

posted @ 2018-11-08 10:59  明天OoO你好  阅读(487)  评论(0编辑  收藏  举报