欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中aiohttp的簡單使用

 更新時(shí)間:2023年03月28日 09:26:54   作者:小Pawn爺  
aiohttp是Python中一個(gè)強(qiáng)大的異步HTTP客戶端和服務(wù)器框架,它可以幫助開發(fā)者快速構(gòu)建高性能的Web應(yīng)用程序。本文將介紹aiohttp的基本概念、使用方法和常見應(yīng)用場景,幫助讀者更好地了解和使用這個(gè)優(yōu)秀的框架

1.定義

aiohttp 是一個(gè)基于 asyncio 的異步 HTTP 網(wǎng)絡(luò)模塊,它既提供了服務(wù)端,又提供了客戶端

2.基本使用

import aiohttp
import asyncio


async def fetch(session, url):
? ? # 聲明一個(gè)支持異步的上下文管理器
? ? async with session.get(url) as response:
? ? ? ? # response.text()是coroutine對象 需要加await
? ? ? ? return await response.text(), response.status


async def main():
? ? # 聲明一個(gè)支持異步的上下文管理器
? ? 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 及以后,不需要顯式聲明事件循環(huán),可以使用 asyncio.run(main())來代替最后的啟動(dòng)操作
? ? 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.相應(yīng)字段

print('status:', response.status) # 狀態(tài)碼
print('headers:', response.headers)# 響應(yīng)頭
print('body:', await response.text())# 響應(yīng)體
print('bytes:', await response.read())# 響應(yīng)體二進(jìn)制內(nèi)容
print('json:', await response.json())# 響應(yīng)體json數(shù)據(jù)

5.超時(shí)設(shè)置

import aiohttp
import asyncio
async def main():
   #設(shè)置 1 秒的超時(shí) 
   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.并發(fā)限制

import asyncio
import aiohttp
# 聲明最大并發(fā)量為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.實(shí)際應(yīng)用

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

到此這篇關(guān)于Python中aiohttp的簡單使用的文章就介紹到這了,更多相關(guān)Python aiohttp 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 使用VLC實(shí)現(xiàn)自動(dòng)播放視頻的操作方法

    使用VLC實(shí)現(xiàn)自動(dòng)播放視頻的操作方法

    VLC是一款開源的多媒體播放器,它支持大量的視頻和音頻格式,并且具有強(qiáng)大的腳本和編程接口,這篇文章主要介紹了使用VLC實(shí)現(xiàn)自動(dòng)播放視頻,需要的朋友可以參考下
    2024-03-03
  • python上下文管理器使用場景及異常處理

    python上下文管理器使用場景及異常處理

    這篇文章主要為大家介紹了python上下文管理器使用場景及異常處理示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • Python繪圖之turtle庫的基礎(chǔ)語法使用

    Python繪圖之turtle庫的基礎(chǔ)語法使用

    這篇文章主要給大家介紹了關(guān)于Python繪圖之turtle庫的基礎(chǔ)語法使用的相關(guān)資料, Turtle庫是Python語言中一個(gè)很流行的繪制圖像的函數(shù)庫,再繪圖的時(shí)候經(jīng)常需要用到的一個(gè)庫需要的朋友可以參考下
    2021-06-06
  • Python切換pip源兩種方法(解決pip?install慢)

    Python切換pip源兩種方法(解決pip?install慢)

    這篇文章主要給大家介紹了關(guān)于Python切換pip源兩種方法(解決pip?install慢),我總結(jié)的這幾種更換pip源的常用方式,希望可以幫助您成功配置國內(nèi)源,解決安裝Python包速度慢的問題,需要的朋友可以參考下
    2023-11-11
  • 深入淺析python3 依賴倒置原則(示例代碼)

    深入淺析python3 依賴倒置原則(示例代碼)

    今天通過園區(qū)停車信息這樣一個(gè)場景分析python3 依賴倒置原則,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2021-07-07
  • Python3內(nèi)置json模塊編碼解碼方法詳解

    Python3內(nèi)置json模塊編碼解碼方法詳解

    Python3中我們利用內(nèi)置模塊json解碼和編碼JSON對象。json模塊提供了四個(gè)功能:dumps、dump、loads、load本文詳細(xì)講解了Python3內(nèi)置json模塊的詳細(xì)使用方法
    2021-10-10
  • 使用Python的Tornado框架實(shí)現(xiàn)一個(gè)Web端圖書展示頁面

    使用Python的Tornado框架實(shí)現(xiàn)一個(gè)Web端圖書展示頁面

    Tornado是Python的一款高人氣Web開發(fā)框架,這里我們來展示使用Python的Tornado框架實(shí)現(xiàn)一個(gè)Web端圖書展示頁面的實(shí)例,通過該實(shí)例可以清楚地學(xué)習(xí)到Tornado的模板使用及整個(gè)Web程序的執(zhí)行流程.
    2016-07-07
  • Pycharm+Python+PyQt5使用詳解

    Pycharm+Python+PyQt5使用詳解

    這篇文章主要介紹了Pycharm+Python+PyQt5使用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • python刪除列表中特定元素的幾種方法

    python刪除列表中特定元素的幾種方法

    這篇文章主要介紹了python刪除列表中特定元素的幾種方法,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)價(jià)值,需要的小伙伴可以參考一下
    2022-05-05
  • 關(guān)于python中第三方庫交叉編譯的問題

    關(guān)于python中第三方庫交叉編譯的問題

    這篇文章主要介紹了python及第三方庫交叉編譯,通過交叉編譯工具,我們就可以在CPU能力很強(qiáng)、存儲(chǔ)控件足夠的主機(jī)平臺(tái)上(比如PC上)編譯出針對其他平臺(tái)的可執(zhí)行程序,需要的朋友可以參考下
    2022-09-09

最新評論