Python中aiohttp的简单使用

 更新时间:2023年03月28日 09:26:54   作者:小Pawn爷  
aiohttp是Python中一个强大的异步HTTP客户端和服务器框架,它可以帮助开发者快速构建高性能的Web应用程序。本文将介绍aiohttp的基本概念、使用方法和常见应用场景,帮助读者更好地了解和使用这个优秀的框架

1.定义

aiohttp 是一个基于 asyncio 的异步 HTTP 网络模块,它既提供了服务端,又提供了客户端

2.基本使用

import aiohttp
import asyncio


async def fetch(session, url):
    # 声明一个支持异步的上下文管理器
    async with session.get(url) as response:
        # response.text()是coroutine对象 需要加await
        return await response.text(), response.status


async def main():
    # 声明一个支持异步的上下文管理器
    async with aiohttp.ClientSession() as session:
        html, status = await fetch(session, 'https://cuiqingcai.com')
        print(f'html: {html[:100]}...')
        print(f'status: {status}')


if __name__ == '__main__':
    #  Python 3.7 及以后,不需要显式声明事件循环,可以使用 asyncio.run(main())来代替最后的启动操作
    asyncio.get_event_loop().run_until_complete(main())

3.请求类型

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')

4.相应字段

print('status:', response.status) # 状态码
print('headers:', response.headers)# 响应头
print('body:', await response.text())# 响应体
print('bytes:', await response.read())# 响应体二进制内容
print('json:', await response.json())# 响应体json数据

5.超时设置

import aiohttp
import asyncio
async def main():
   #设置 1 秒的超时 
   timeout = aiohttp.ClientTimeout(total=1)
   async with aiohttp.ClientSession(timeout=timeout) as session:
       async with session.get('https://httpbin.org/get') as response:
           print('status:', response.status)
if __name__ == '__main__':
   asyncio.get_event_loop().run_until_complete(main())

6.并发限制

import asyncio
import aiohttp
# 声明最大并发量为5
CONCURRENCY = 5
semaphore = asyncio.Semaphore(CONCURRENCY)
URL = 'https://www.baidu.com'

session = None
async def scrape_api():
   async with semaphore:
       print('scraping', URL)
       async with session.get(URL) as response:
           await asyncio.sleep(1)
           return await response.text()
    
async def main():
   global session
   session = aiohttp.ClientSession()
   scrape_index_tasks = [asyncio.ensure_future(scrape_api()) for _ in range(10000)]
   await asyncio.gather(*scrape_index_tasks)
if __name__ == '__main__':
   asyncio.get_event_loop().run_until_complete(main())

7.实际应用

import asyncio
import aiohttp
import logging
import json
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s: %(message)s')
INDEX_URL = 'https://dynamic5.scrape.center/api/book/?limit=18&offset={offset}'
DETAIL_URL = 'https://dynamic5.scrape.center/api/book/{id}'
PAGE_SIZE = 18
PAGE_NUMBER = 100
CONCURRENCY = 5

semaphore = asyncio.Semaphore(CONCURRENCY)
session = None

async def scrape_api(url):
   async with semaphore:
       try:
           logging.info('scraping %s', url)
           async with session.get(url) as response:
               return await response.json()
       except aiohttp.ClientError:
           logging.error('error occurred while scraping %s', url, exc_info=True)

async def scrape_index(page):
   url = INDEX_URL.format(offset=PAGE_SIZE * (page - 1))
   return await scrape_api(url)

async def main():
   global session
   session = aiohttp.ClientSession()
   scrape_index_tasks = [asyncio.ensure_future(scrape_index(page)) for page in range(1, PAGE_NUMBER + 1)]
   results = await asyncio.gather(*scrape_index_tasks)
   logging.info('results %s', json.dumps(results, ensure_ascii=False, indent=2))
   

if __name__ == '__main__':
   asyncio.get_event_loop().run_until_complete(main())

到此这篇关于Python中aiohttp的简单使用的文章就介绍到这了,更多相关Python aiohttp 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python中判断输入是否为数字的实现代码

    Python中判断输入是否为数字的实现代码

    这篇文章主要介绍了Python中判断输入是否为数字的实现代码,需要的朋友可以参考下
    2018-05-05
  • pandas dataframe统计填充空值方式

    pandas dataframe统计填充空值方式

    这篇文章主要介绍了pandas dataframe统计填充空值方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • python selenium循环登陆网站的实现

    python selenium循环登陆网站的实现

    这篇文章主要介绍了python selenium循环登陆网站的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • Python设计模式之桥接模式原理与用法实例分析

    Python设计模式之桥接模式原理与用法实例分析

    这篇文章主要介绍了Python设计模式之桥接模式原理与用法,结合具体实例形式分析了Python桥接模式的相关概念、原理、定义及使用方法,需要的朋友可以参考下
    2019-01-01
  • Pycharm新建项目时报错解决办法

    Pycharm新建项目时报错解决办法

    pycharm可以很方便的管理Python的解释器(如果安装了多个的话),以及第三方模块,包,下面这篇文章主要给大家介绍了关于Pycharm新建项目时报错解决的相关资料,需要的朋友可以参考下
    2023-06-06
  • Python如何创建装饰器时保留函数元信息

    Python如何创建装饰器时保留函数元信息

    这篇文章主要介绍了Python如何创建装饰器时保留函数元信息,文中讲解非常细致,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-08-08
  • Keras设置以及获取权重的实现

    Keras设置以及获取权重的实现

    这篇文章主要介绍了Keras设置以及获取权重的实现,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • 解决Python字典查找报Keyerror的问题

    解决Python字典查找报Keyerror的问题

    这篇文章主要介绍了解决Python字典查找报Keyerror的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • python实现文件+参数发送request的实例代码

    python实现文件+参数发送request的实例代码

    这篇文章主要介绍了python实现文件+参数发送request的实例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • Python中easy_install 和 pip 的安装及使用

    Python中easy_install 和 pip 的安装及使用

    本篇文章主要介绍了Python中easy_install 和 pip 的安装及使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06

最新评论