python async异步编程(asyncio 学python必备)UP主:武沛齐
- yield 装饰器
- @asyncio.coroutine
- request
response = request.get(url)
filename = url.rsplit('_')[-1]
with open (filename, mode = 'wb') as file_object:
b
file_object.write(response.content)
aiohttp
async def fetch(session, url)
async with session.get(url, verify_ssl = false) as reponse:
content = await response.content.read()
async def main():
async with aiohttp.ClientSession() as sessiion:
url_list = [...]
tasks = [async.creat_task(fetch(session,url))for url in url_list ]
await asyncio.wait(tasks)
- async with:异步上下文管理器, session.get() 一个上下文管理器对象,
Q1:async def和def有什么区别?能否这样理解:若函数中出现async语句,则必须使用async def?
- 普通函数
- 是同步执行的,调用时会立即执行函数体中的代码,直到函数返回。
- 它们是阻塞式的,即在函数执行期间,程序的其他部分无法运行。
- 异步函数
- 异步执行,调用时不会立即执行函数体中的代码,而是返回一个
coroutine对象。
- 需要使用 await 或 asyncio.run() 等方式来执行。
- 它们是非阻塞式的,允许程序在等待异步操作完成时执行其他任务。
- 在函数定义中使用 async def ,表示该函数是一个异步函数。
- 在函数体内使用 await ,表示暂停当前任务的执行,等待异步操作完成。
- 如果函数体内使用了 await ,则必须使用 async def 定义该函数。
- 如果函数体内没有使用 await ,但仍然使用了 async def ,虽然语法上没有错误,但这种写法通常没有意义,因为函数体不会执行任何异步操作。
Q2: