python+asyncio发送请求

import asyncio
import aiohttp
import json
def fetch_page(url):
    try:
        response = yield from aiohttp.request('GET', url)
        string = (yield from response.read()).decode('utf-8')
        if response.status == 200:
            data = json.loads(string)
            print(data)
        else:
            print("data fetch failed for")
            print(response.content, response.status)
    except asyncio.TimeoutError:
        print("访问失败")
if __name__ == '__main__':
    url = 'http://gc.ditu.aliyun.com/geocoding?a=%E8%8B%8F%E5%B7%9E%E5%B8%82'
    # urls = [url] * 4
    loop = asyncio.get_event_loop()
    tasks = []
    for i in range(5):
        tasks.append(asyncio.async(fetch_page(url)))
    # tasks = [asyncio.async(fetch_page(z, i)) for i, z in enumerate(urls)]
    print(tasks)
    loop.run_until_complete(asyncio.wait(tasks, timeout=5))
    loop.close()

封装一次

class fetch():
    def __init__(self, dict_http):
        '''
        http请求的封装,传入dict
        :param dict_http:
        '''
        self.dict_http = dict_http
    def get(self, url, param):
        data = {}
        url = self.dict_http["protocol"] + self.dict_http["host"] + ":" + str(self.dict_http["port"]) + url
        print(url)
        try:
            response = yield from aiohttp.request("GET", url, headers=self.dict_http["header"], params=param)
            string = (yield from response.read()).decode('utf-8')
            if response.status == 200:
                data = json.loads(string)
            else:
                print("data fetch failed for")
                print(response.content, response.status)
            data["status_code"] = response.status
            print(data)
        except asyncio.TimeoutError:
            print("访问失败")
        return data
    def post(self,url, param):
        data = {}
        url = self.dict_http["protocol"] + self.dict_http["host"] + ':' + str(self.dict_http["port"]) + url
        try:
            response = yield from aiohttp.request('POST', url, data=param)
            string = (yield from response.read()).decode('utf-8')
            if response.status == 200:
                data = json.loads(string)
            else:
                print("data fetch failed for")
                print(response.content, response.status)
            data["status_code"] = response.status
            print(data)
        except asyncio.TimeoutError:
            print("访问失败")
        return data
if __name__ == '__main__':
    url = '/iplookup/iplookup.php'
    loop = asyncio.get_event_loop()
    tasks = []
    dict_http = {}
    dict_http["protocol"] = "http://"
    dict_http["host"] = "int.dpool.sina.com.cn"
    dict_http["port"] = 80
    dict_http["header"] = {"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36"}
    f = fetch(dict_http)
    for i in range(2):
        tasks.append(asyncio.async(f.get(url, param="format=json&ip=218.4.255.255")))
    loop.run_until_complete(asyncio.wait(tasks, timeout=5))
    loop.close()

你可能感兴趣的:(python+asyncio发送请求)