# -*- coding: utf-8 -*-
# @Time : 2018/8/20 14:35
# @Author : cxa
# @File : chttp.py
# @Software: PyCharm
# !/usr/bin/env python3
# -*- coding: utf-8 -*- from functools import partial, wraps
from random import random
import asyncio, os
from cchardet import detect try:
import aiohttp
except ImportError:
raise RuntimeError('您没有安装aiohttp,请执行安装命令 pip install aiohttp ') result, all_tasks, connector, sessiondict = [], [], [], {} class AhttpRequest():
def __init__(self, method, url, timeout=None, session=False, headers=None, cookies=None, unsafe=None,
mark='1111111111', **kwargs):
self.method, self.session, self.url, self.mark, self.timeout = method, session, url, mark, timeout
callback = kwargs.pop('callback', None)
self.callback = callback
self.kwargs = kwargs
if not session:
self.sessiondict = (cookies, headers, aiohttp.CookieJar(unsafe=True) if unsafe else None) def run(self, pool=5, exception_handle=None):
result = run([self], pool=pool, exception_handle=exception_handle)
return result[0] class WithSession():
def __init__(self, mark, session=True):
self.get = partial(AhttpRequest, 'GET', session=session, mark=mark)
self.options = partial(AhttpRequest, 'OPTIONS', session=session, mark=mark)
self.head = partial(AhttpRequest, 'HEAD', session=session, mark=mark)
self.post = partial(AhttpRequest, 'POST', session=session, mark=mark)
self.put = partial(AhttpRequest, 'PUT', session=session, mark=mark)
self.patch = partial(AhttpRequest, 'PATCH', session=session, mark=mark)
self.delete = partial(AhttpRequest, 'DELETE', session=session, mark=mark) get = partial(AhttpRequest, 'GET')
options = partial(AhttpRequest, 'OPTIONS')
head = partial(AhttpRequest, 'HEAD')
post = partial(AhttpRequest, 'POST')
put = partial(AhttpRequest, 'PUT')
patch = partial(AhttpRequest, 'PATCH')
delete = partial(AhttpRequest, 'DELETE') class ClientSession(aiohttp.ClientSession):
def close(self):
"""
对ClientSession类的close方法进行重写
"""
if not self.closed:
if self._connector_owner:
self._connector.close()
connector.append(self._connector) return 'ClientSession.close() is a coroutine' def Session(cookies=None, headers=None, unsafe=None):
mark = str(round(random() * 10 ** 10))
sessiondict[mark] = (cookies, headers, aiohttp.CookieJar(unsafe=True) if unsafe else None)
return WithSession(mark=mark) def run(tasks, pool=2, exception_handle=None):
del result[:]
del connector[:]
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(go(tasks, pool, exception_handle, loop=loop))
loop.run_until_complete(future)
# loop.close()
return result class AhttpResponse():
def __init__(self, content, clientResponse):
self.content = content
self.clientResponse = clientResponse def raw(self):
return self.clientResponse @property
def url(self):
return self.clientResponse.url @property
def cookies(self):
return self.clientResponse.cookies @property
def headers(self):
return self.clientResponse.headers @property
def status(self):
return self.clientResponse.status @property
def method(self):
return self.clientResponse.method def text(self, encoding=None):
encoding = encoding or detect(self.content)['encoding']
return self.content.decode(encoding=encoding) def __repr__(self):
return "<AhttpResponse [status {}]>".format(self.clientResponse.status) __str__ = __repr__ async def go(tasks, pool, exception_handle, loop):
del all_tasks[:]
conn = aiohttp.TCPConnector(use_dns_cache=True, loop=loop, verify_ssl=False)
sem = asyncio.Semaphore(pool)
classify = {}
[classify[i.mark].append(i) if classify.get(i.mark, 0) else classify.setdefault(i.mark, [i]) for i in tasks]
print(classify)
try:
for i in classify.pop('1111111111'):
all_tasks.append(control_sem(sem, i, exception_handle, session=False))
except:
pass
for i in classify:
async with ClientSession(cookies=sessiondict[i][0], headers=sessiondict[i][1], cookie_jar=sessiondict[i][2],
connector_owner=False, connector=conn) as locals()['session{}'.format(i)]:
for j in classify[i]:
all_tasks.append(control_sem(sem, j, exception_handle, session=locals()['session{}'.format(i)])) await asyncio.wait(all_tasks)
# 关闭所有连接
for i in connector:
i.close()
return True async def fetch(session, i, exception_handle):
try:
if session:
async with session.request(i.method, i.url, timeout=i.timeout, **(i.kwargs)) as resp:
content = await resp.read()
myAhttp = AhttpResponse(content, resp)
else:
async with aiohttp.ClientSession(cookies=i.sessiondict[0], headers=i.sessiondict[1],
cookie_jar=i.sessiondict[2]) as session2:
async with session2.request(i.method, i.url, timeout=i.timeout, **(i.kwargs)) as resp:
content = await resp.read()
myAhttp = AhttpResponse(content, resp) if i.callback:
try:
i.callback(myAhttp)
except:
pass
except Exception as e:
myAhttp = None
exception_handle and exception_handle(i, e) finally:
result.append(myAhttp) async def control_sem(sem, i, exception_handle, session):
# 限制信号量
async with sem:
await fetch(session, i, exception_handle) # __all__ = (
# 'Session', 'get', 'options', 'head', 'post', 'put', 'patch', 'delete'
# ) if __name__ == '__main__':
urls = ["http://www.runoob.com/python/att-time-mktime.html",
"https://blog.csdn.net/getcomputerstyle/article/details/71515331"]

ahttp的更多相关文章

  1. CocoaPods使用 主要带图。转载。

    原文地址 快速更新,不需要查找更新库 命令:pod update  --verbose --no-repo-update 虽然网上关于CocoaPods安装教程多不胜数,但是我在安装的过程中还是出现了 ...

  2. 网站统计中的数据收集原理及实现(share)

    转载自:http://blog.codinglabs.org/articles/how-web-analytics-data-collection-system-work.html 网站数据统计分析工 ...

  3. CocoaPods 安装

    虽然网上关于CocoaPods安装教程多不胜数,但是我在安装的过程中还是出现了很多错误,所以大家可以照下来步骤装一下,我相信会很好用. 前言 在iOS项目中使用第三方类库可以说是非常常见的事,但是要正 ...

  4. 使用nginx lua实现网站统计中的数据收集

    导读网站数据统计分析工具是各网站站长和运营人员经常使用的一种工具,常用的有 谷歌分析.百度统计和腾讯分析等等.所有这些统计分析工具的第一步都是网站访问数据的收集.目前主流的数据收集方式基本都是基于ja ...

  5. How to disable certain HTTP methods (PUT, DELETE, TRACE and OPTIONS) in JBOSS7 .

    Resolution Option 1 -Using RewriteValve (can apply globally) You can use RewriteValve to disable the ...

  6. 使用Nginx和Logstash以及kafka来实现网站日志采集的详细步骤和过程

    使用Nginx和Logstash以及kafka来实现网站日志采集的详细步骤和过程 先列出来总体启动流程: (1)启动zookeeper集群(hadoop01.hadoop02和hadoop03这3台机 ...

  7. cocopods的使用方法

    虽然网上关于CocoaPods安装教程多不胜数,但是我在安装的过程中还是出现了很多错误,所以大家可以照下来步骤装一下,我相信会很好用. 前言 在iOS项目中使用第三方类库可以说是非常常见的事,但是要正 ...

  8. iOS开发:cocoapods的使用

    Cocoapods是OS X和iOS下的一个第三方类库管理工具,通过CocoaPods工具我们可以为项目添加各种依赖库,减少了我们手动引入库需要的各种配置,同时使用cocoapods可以方便的查找新的 ...

  9. python 站点爬虫 下载在线盗墓笔记小说到本地的脚本

    近期闲着没事想看小说,找到一个全是南派三叔的小说的站点,决定都下载下来看看,于是动手,在非常多QQ群里高手的帮助下(本人正則表達式非常烂.程序复杂的正则都是一些高手指导的),花了三四天写了一个脚本 须 ...

随机推荐

  1. 使用cookie保存用户登录信息

    写入Cookie HttpCookie _cookie = new HttpCookie("User"); _cookie.Values.Add("UserName&qu ...

  2. python写BMI指数菜单

    需求: # 1.创建并输出菜单, 菜单是不可变的. 所以使用元组menus = ("1, 录入", "2, 查询", "3, 删除", &q ...

  3. debug - vue中通过ajax获取数据时,如何避免绑定的数据中出现property of undefined错误

    因为获取服务器是异步的,所以 vue 先绑定数据. 如果 ??? 是通过 ajax 异步获取的,在获取之前,???是未定义的.此时在外面的标签上添加一个 v-if="???" 可以 ...

  4. 【BZOJ1923】外星千足虫(线性基)

    [BZOJ1923]外星千足虫(线性基) 题面 BZOJ 洛谷 Description Input 第一行是两个正整数 N, M. 接下来 M行,按顺序给出 Charles 这M次使用"点足 ...

  5. [知识点]C++中STL容器之vector

    零.STL目录 1.容器之map 2.容器之vector 3.容器之set 一.前言 关于STL和STL容器的概念参见STL系列第一篇——map(见上).今天介绍第二个成员——vector. 二.用途 ...

  6. 洛谷P1991 无线通讯网

    P1991 无线通讯网 170通过 539提交 题目提供者洛谷OnlineJudge 标签图论 难度普及+/提高 提交该题 讨论 题解 记录 最新讨论 怎么又炸了 为啥一直40!求解! UKE:inv ...

  7. C++ ------ 互斥锁、原子操作的性能测试

    atomic原子操作:是在新标准C++11,引入了原子操作的概念,并通过这个新的头文件提供了多种原子操作数据类型,例如,atomic_bool,atomic_int等等 测试程序 #include & ...

  8. mysql5.7中root密码忘记后修改密码

    一.更改my.cnf配置文件 1.用命令编辑/etc/my.cnf配置文件,即:vim /etc/my.cnf 或者 vi /etc/my.cnf 2.在[mysqld]下添加skip-grant-t ...

  9. 远程调试openstack

    之前一直没有找到方法调试openstack的horizon代码,现在终于找到方法了,特别感谢下面这篇博客,讲解非常清晰: http://blog.csdn.net/tantexian/article/ ...

  10. 跟我一起写Makefile(七)

    make 的运行—————— 一般来说,最简单的就是直接在命令行下输入make命令,make命令会找当前目录的makefile来执行,一切都是自动的.但也有时你也许只想让make重编译某些文件,而不是 ...