aiohttp模块1 client
Make a Request
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get('https://api.github.com/events') as resp:
print(resp.status)
print(await resp.text())
session.post('http://httpbin.org/post', data=b'data')
session.put('http://httpbin.org/put', data=b'data')
session.delete('http://httpbin.org/delete')
session.head('http://httpbin.org/get')
session.options('http://httpbin.org/get')
session.patch('http://httpbin.org/patch', data=b'data')
aiohttp.ClientSession.get(self, url, allow_redirects=True, **kwargs)
aiohttp.ClientSession.post(self, url, data=None, **kwargs)
aiohttp.ClientSession.put(self, url, data=None, **kwargs)
aiohttp.ClientSession.delete(self, url, **kwargs)
aiohttp.ClientSession.head(self, url, allow_redirects=False, **kwargs)
aiohttp.ClientSession.options(self, url, allow_redirects=True, **kwargs)
aiohttp.ClientSession.patch(self, url, data=None, **kwargs)
# 无须为每个request建立session. 仅需要为每个application建立session供所有request使用. session内部包含连接池,connection复用与长连接加速总性能。
Passing Parameters In URLs
# 字典
params = {'key1': 'value1', 'key2': 'value2'}
async with session.get('http://httpbin.org/get', params=params) as resp:
assert str(resp.url) == 'http://httpbin.org/get?key2=value2&key1=value1'
# 数组
params = [('key', 'value1'), ('key', 'value2')]
async with session.get('http://httpbin.org/get', params=params) as r:
assert str(r.url) == 'http://httpbin.org/get?key=value2&key=value1'
# 字符串
async with session.get('http://httpbin.org/get', params='key=value+1') as r:
assert str(r.url) == 'http://httpbin.org/get?key=value+1'
# aiohttp在发送请求前在内部自动对url进行转码,如URL('http://example.com/путь%30?a=%31') -> URL('http://example.com/%D0%BF%D1%83%D1%82%D1%8C/0?a=1')
# 使用encoded=True开关禁用, 如await session.get(URL('http://example.com/%30', encoded=True))
Response Content and Status Code
async with session.get('https://api.github.com/events') as resp:
print(resp.status)
print(await resp.text())
# out
200
'[{"created_at":"2015-06-12T14:06:22Z","public":true,"actor":{... '
# aiohttp自动对服务端返回的内容进行decode.可以使用text()方法自定义encode,如 await resp.text(encoding='windows-1251')
Binary Response Content
async with session.get('https://api.github.com/events') as resp:
print(await resp.read())
# out
b'[{"created_at":"2015-06-12T14:06:22Z","public":true,"actor":{... ]'
# gzip和deflate压缩算法,自动解码。brotli压缩算法需要安装 brotlipy 模块
JSON Request
async with aiohttp.ClientSession() as session:
async with session.post(url, json={'test': 'object'})
默认使用标准库json进行序列化,如果想快一点的话,可以使用第三方库ujson,但小小的不兼容
import ujson
async with aiohttp.ClientSession(json_serialize=ujson.dumps) as session:
async with session.post(url, json={'test': 'object'})
JSON Response Content
async with session.get('https://api.github.com/events') as resp:
print(await resp.json())
# 如果json解析失败,会抛出异常
Streaming Response Content
async with aiohttp.StreamReader() as session:
async with session.get('https://api.github.com/events') as resp:
await resp.content.read(10)
# read(), json(),text()将内容放在内存中,如果文件内容比较大,1G以上,需要使用 aiohttp.StreamReader 替代,它会对gzip和deflate压缩算法自动解码
with open(filename, 'wb') as fd:
while True:
chunk = await resp.content.read(chunk_size)
if not chunk:
break
fd.write(chunk)
# 写入文件
More complicated POST requests
payload = {'key1': 'value1', 'key2': 'value2'}
async with session.post('http://httpbin.org/post',
data=payload) as resp:
print(await resp.text())
# form-encoded data (HTML form), 使用字典,字典数据自动编码为form-encoded
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
async with session.post(url, data=b'\x00Binary-data\x00') as resp:
...
# 非 form-encoded数据使用bytes类型,数据发送默认使用content-type ‘application/octet-stream’
async with session.post(url, json={'example': 'test'}) as resp:
...
# josn类型
async with session.post(url, text='Тест') as resp:
...
# content-type text类型
POST a Multipart-Encoded File
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
await session.post(url, data=files)
url = 'http://httpbin.org/post'
data = FormData()
data.add_field('file',
open('report.xls', 'rb'),
filename='report.xls',
content_type='application/vnd.ms-excel')
await session.post(url, data=data)
# 上传文件对象,aiohttp使用stream
Streaming uploads
with open('massive-body', 'rb') as f:
await session.post('http://httpbin.org/post', data=f)
# 文件类型过大,使用Stream方式
@aiohttp.streamer
def file_sender(writer, file_name=None):
with open(file_name, 'rb') as f:
chunk = f.read(2**16)
while chunk:
yield from writer.write(chunk)
chunk = f.read(2**16)
# Then you can use file_sender as a data provider:
async with session.post('http://httpbin.org/post',
data=file_sender(file_name='huge_file')) as resp:
print(await resp.text())
async def feed_stream(resp, stream):
h = hashlib.sha256()
while True:
chunk = await resp.content.readany()
if not chunk:
break
h.update(chunk)
stream.feed_data(chunk)
return h.hexdigest()
resp = session.get('http://httpbin.org/post')
stream = StreamReader()
loop.create_task(session.post('http://httpbin.org/post', data=stream))
file_hash = await feed_stream(resp, stream)
r = await session.get('http://python.org')
await session.post('http://httpbin.org/post', data=r.content)
WebSockets
session = aiohttp.ClientSession()
async with session.ws_connect('http://example.org/websocket') as ws:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close cmd':
await ws.close()
break
else:
await ws.send_str(msg.data + '/answer')
elif msg.type == aiohttp.WSMsgType.CLOSED:
break
elif msg.type == aiohttp.WSMsgType.ERROR:
break
Timeouts
async with session.get('https://github.com', timeout=60) as r:
...
# 默认IO操作延时5分钟,None 或者 0 禁用延时
# 使用async_timeout模块
import async_timeout
with async_timeout.timeout(0.001):
async with session.get('https://github.com') as r:
await r.text()
aiohttp模块1 client的更多相关文章
- SocketServer模块,hmac模块验证client合法性
hmac模块: 1.模块初识: import hmac # h = hmac.new() #括号里要给它连个bytes类型,一个是自定义的secret_key,一个是你想进行加密的bytes # 密文 ...
- Python学习---IO的异步[asyncio +aiohttp模块]
aiohttp aiohttp是在asyncio模块基础上封装的一个支持HTTP请求的模块,内容比8.4.2[基于asyncio实现利用TCP模拟HTTP请求]更全面 安装aiohttp: pip3 ...
- Python3中的http.client模块
http 模块简介 Python3 中的 http 包中含有几个用来开发 HTTP 协议的模块. http.client 是一个底层的 HTTP 协议客户端,被更高层的 urllib.request ...
- aiohttp 支持异步的网络请求模块
通常在进行网络数据采集时候我们会用到requests,urllib等模块,但是这些模块在使用中并不支持异步,所以今天我们介绍一个支持异步网络请求的模块aiohttp. 首先我们使用flask简单的搭一 ...
- python的异步IO模块
asyncio模块:示例一 import asyncio @asyncio.coroutine def func1(): print('before...func1......') yield fro ...
- asynicio模块以及爬虫应用asynicio模块(高性能爬虫)
一.背景知识 爬虫的本质就是一个socket客户端与服务端的通信过程,如果我们有多个url待爬取,只用一个线程且采用串行的方式执行,那只能等待爬取一个结束后才能继续下一个,效率会非常低. 需要强调的是 ...
- 爬虫模块之解决IO
一 asyncio模块 asyncio模块:主要是帮我们检测IO(只能是网路IO). @asyncio.coroutine:装饰器 tasks:任务列表 get_event_loop:起任务 run_ ...
- 高性能爬虫——asynicio模块
一 背景知识 爬虫的本质就是一个socket客户端与服务端的通信过程,如果我们有多个url待爬取,只用一个线程且采用串行的方式执行,那只能等待爬取一个结束后才能继续下一个,效率会非常低. 需要强调 ...
- 异步网络编程aiohttp的使用
aiohttp的使用 aiohttp Asynchronous HTTP Client/Server for asyncio and Python. Supports both Client and ...
随机推荐
- HDU-2063(二分图匹配模板题)
过山车Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submissi ...
- plot over time
先选择监测点 最后输出,由于所有数据都被输出,因此需要等待久一点 可以勾选需要的值,记得更换勾选变量后再次点击apply 最后的效果: 最后可以把数据写出来做后处理 输出后的数据:
- rest-assured之静态导入及简单使用实例
一.静态导入 为了有效的使用rest-assured,官网推荐从下列class中静态导入方法: io.restassured.RestAssured.* io.restassured.matcher. ...
- 清华集训2017D2T1 小 Y 和地铁(metro)
题目:https://www.luogu.org/problem/show?pid=P4005 题意:一条线段,给定n个点(n<=44)其中每个点可能对应另外一个点.如果一个点有对应点,那么就要 ...
- [HAOI2018]反色游戏
[Luogu4494] [BZOJ5303] [LOJ2524] LOJ有数据就是好 原题解,主要是代码参考 对于每一个联通块(n个点),其他的边一开始随便选,只需要n-1条边就可以确定最终结果. 所 ...
- 【算法笔记】B1021 个位数统计
1021 个位数统计 (15 分) 给定一个 k 位整数 N=dk−110k−1+⋯+d1101+d0 (0≤di≤9, i=0,⋯,k−1, dk−1> ...
- CF248E Piglet's Birthday(概率dp)
题面 luogu CodeForces 题解 \(orz\) yyb 转移蜜罐其实是吓唬人的...... 转移的蜜罐都是尝试过的,所有只关心当前架子上的蜜罐数 设\(f[i][j]\)表示第i个货架有 ...
- POJ_1733 Parity game 【并查集+离散化】
一.题面 POJ1733 二.分析 该题与之前做过的带权并查集的唯一区别就是数组开不下.所以需要用离散化的思想,只取那些有用的点来解决该问题. 离散化其实就是把这些所有用到的点收集后,去重,再排一下序 ...
- Oracle sql 中的 ALL,ANY,SOME
[转自] http://www.itpub.net/thread-1355835-1-1.html any和some是等价的,其与all的前面都只能是比较符号,即=, !=, >, <, ...
- js 递归思想 处理后台多维数组的数据 之 完美契合
不多BB! 直接看源码 get(tree = []) { let self = this let arr = []; if (!!tree && tree.length !== 0) ...