异步Python真的是异步的吗?

时间:2018-06-28 16:14:52

标签: python asynchronous python-asyncio aiohttp

使用Python 3.6和aiohttpfrom aiohttp import ClientSession import asyncio, ssl, time base_url = 'https://my-base-url.com/api' async def fetch(session, id): query_params = {'qp1':'v1','qp2':'v2', 'id': id} async with session.get(base_url, params=query_params, ssl=ssl.SSLContext()) as response: res_json = await response.json() if response.status == 200: time.sleep(2) min_rating = res_json.get('minRating') max_rating = res_json.get('maxRating') print("id = %s, min = %s, max = %s" % (id, min_rating, max_rating)) async def run(ids): tasks = [] async with ClientSession() as session: for id in ids: task = asyncio.ensure_future(fetch(session, id)) tasks.append(task) responses = await asyncio.gather(*tasks) return responses if __name__ == '__main__': ids = [123, 456, 789] future = asyncio.ensure_future(run(ids)) event_loop = asyncio.get_event_loop() event_loop.run_until_complete(future) print("\n\ndone") ,我编写了一个简单的异步程序:

time.sleep(2)

fetch(session, id)中的sleep使得该程序似乎不是异步的,因为它得到一个响应,睡眠,另一个响应,睡眠等等。当我删除睡眠调用时,它似乎是异步/并发的,因为响应以随机顺序返回。 import sys from PyQt5.QtCore import Qt, QRectF from PyQt5.QtGui import QPainter from PyQt5.QtWidgets import QCalendarWidget, QApplication class CalendarWidget(QCalendarWidget): def paintCell(self, painter, rect, date): painter.setRenderHint(QPainter.Antialiasing, True) if (date.day() == 1) or (date.day() == 15): painter.save() painter.drawRect(rect) painter.setPen(Qt.blue) painter.drawText(QRectF(rect), Qt.TextSingleLine|Qt.AlignCenter, str(date.day())) painter.restore() else: QCalendarWidget.paintCell(self, painter, rect, date) if __name__ == '__main__': app = QApplication(sys.argv) w = CalendarWidget() w.show() sys.exit(app.exec_()) 在这种情况下正在做什么?是否锁定所有线程?为什么它看起来是顺序的而不是并行的?

1 个答案:

答案 0 :(得分:5)

time.sleep(2)是一个同步(阻塞)调用,因此要停止它的异步调用,应使用await asyncio.sleep(2),它将“释放”资源。