Python學習---Python的非同步---asyncio模組(no-http)

來源:互聯網
上載者:User

標籤:pre   發送資料   回調   cti   pad   text   result   syn   info   

Asyncio進行非同步IO請求操作:

1. @asyncio.coroutine  裝飾任務函數

2. 函數內配合yield from 和裝飾器@asyncio.coroutine 配合使用【固定格式】

3. loop = asyncio.get_event_loop()

loop.run_until_complete(asyncio.gather(*tasks)) # 接受非同步IO的任務並非同步執行任務

執行個體一:

非同步IO: 協程機制 + 回呼函數

import asyncio@asyncio.coroutine  # 裝飾任務函數def func1():    print(‘before...func1......‘)    # yield from 和裝飾器@asyncio.coroutine 配合使用【固定格式】    yield from asyncio.sleep(5)  # 必須寫asyncio才表示非同步IO執行5秒,time.sleep(5)不生效    print(‘5秒後...‘)    print(‘end...func1......‘)tasks = [func1(), func1()]# 事件迴圈: 對涉及非同步,協成,阻塞等IO操作時進行事件的迴圈操作loop = asyncio.get_event_loop()loop.run_until_complete(asyncio.gather(*tasks)) # 接受非同步IO的任務並非同步執行任務loop.close()

AsyncIO缺點:

不支援HTTP請求,也就是說不能直接發送URL過去進行訪問

支援TCP請求,也就是說可以發送【IP+端】進行訪問

註:HTTP在TCP之上

基於asyncio實現利用TCP類比HTTP請求

import asyncio# 基於asyncio實現利用TCP類比HTTP請求[asyncio實際上不支援HTTP請求]@asyncio.coroutinedef fetch_async(host, url=‘/‘):    print(‘HOST和URL資訊:‘, host, url)    # reader: 用於讀取串連的資訊    # writer: 用於給伺服器寫資訊    reader, writer = yield from asyncio.open_connection(host, 80)    # 基於TCP類比的HTTP請求:要求標頭header和請求體body之間是2空行【\r\n\r\n】分隔的    request_header_content = """GET %s HTTP/1.0\r\nHost: %s\r\n\r\n""" % (url, host,)    request_header_content = bytes(request_header_content, encoding=‘utf-8‘) # 字串轉換位元組    writer.write(request_header_content) # 準備發送資料給伺服器    # drain: 英文翻譯為喝光,這裡作發送完成理解    yield from writer.drain() # 發送資料給伺服器,此時可能會阻塞執行個請求,考慮資料量大等原因    text = yield from reader.read() # 等待返回的資料,text就是先收到回複的請求完成後等待其他返回    print(host,url,‘返回後的結果:‘, text)    writer.close() # 關閉流tasks = [    fetch_async(‘www.cnblogs.com‘, ‘/ftl1012/‘),    fetch_async(‘www.dig.chouti.com‘, ‘/images/homepage_download.png‘)]loop = asyncio.get_event_loop()results = loop.run_until_complete(asyncio.gather(*tasks))loop.close()

基於TCP類比HTTP詳解:

Python學習---Python的非同步---asyncio模組(no-http)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.