python asyncio 异步编程-协程 2

asyncio 异步编程

官方文档:

  • 中文版:https://docs.python.org/zh-cn/3.8/library/asyncio.html
  • 英文本:https://docs.python.org/3.8/library/asyncio.html

1. 事件循环

事件循环 是指主线程每次将执行序列中的任务清空后,就去事件队列中检查是否有等待执行的任务,如果有则每次取出一个推到执行序列中执行,这个过程是循环往复的。

理解成一个死循环,去检测并执行某些代码。

事件循环是每个 asyncio 应用的核心。 事件循环会运行异步任务和回调,执行网络 IO 操作,以及运行子进程。

应用开发者通常应当使用高层级的 asyncio 函数,例如 asyncio.run(),应当很少有必要引用循环对象或调用其方法。

# 伪代码任务列表 = [ 任务1, 任务2, 任务3,... ]while True:可执行的任务列表,已完成的任务列表 = 去任务列表中检查所有的任务,将'可执行''已完成'的任务返回for 就绪任务 in 已准备就绪的任务列表:执行已就绪的任务for 已完成的任务 in 已完成的任务列表:在任务列表中移除 已完成的任务如果 任务列表 中的任务都已完成,则终止循环
import asyncio# 去生成或获取一个事件循环
loop = asyncio.get_event_loop()# 将任务放到 '任务列表'
loop.run_until_complete(任务)

2. 详解

2.1 async

协程函数,定义函数时候 async def 函数名

协程对象,执行 协程函数() 得到的协程对象

async def func():  # 定义一个协程函数passresult = func()   # 获取协程对象(此时函数内部代码不会被执行)

注:加上事件循环才能执行协程函数内部代码,即将协程对象交给事件循环来处理

import asyncioasync def func():print('人生苦短,我用python')result = func()# loop = asyncio.get_event_loop()
# loop.run_until_complete(result)
asyncio.run(result)  # 等价与上面两行,python3.7之后引入的便捷方式

2.2 await

await + 可等待对象(协程对象、Future、Task对象 —> IO等待)

2.2.1 协程对象

协程对象,执行 协程函数() 得到的是协程对象。

示例1:

import asyncioasync def func():print('人生苦短,')response = await asyncio.sleep(2)print('我用python', response)asyncio.run(func()).# 结果:
"""
人生苦短,
我用python None
"""

示例2:

import asyncioasync def others():print('人生苦短,')await asyncio.sleep(2)print('我用python')return '返回值'async def func():print('执行协程函数内部代码--->')# 遇到IO操作挂起当前协程任务,等IO操作完成之后再继续往下执行,当前协程挂起时,事件循环可以去执行其他协程任务response = await others()print('IO请求结束,结果为:', response)asyncio.run(func())"""
执行协程函数内部代码--->
人生苦短,
我用python
IO请求结束,结果为: 返回值
"""

示例3:

import asyncioasync def others():print('人生苦短,')await asyncio.sleep(2)print('我用python')return '返回值'async def func():print('执行协程函数内部代码--->')# 遇到IO操作挂起当前协程任务,等IO操作完成之后再继续往下执行,当前协程挂起时,事件循环可以去执行其他协程任务response1 = await others()print('IO请求结束,结果为:', response1)response2 = await others()print('IO请求结束,结果为:', response2)asyncio.run(func())
"""
执行协程函数内部代码--->
人生苦短,
我用python
IO请求结束,结果为: 返回值
人生苦短,
我用python
IO请求结束,结果为: 返回值
"""

await 就是 等待对象的值得到结果之后在继续往下执行

2.2.2 Task对象

在事件循环中添加多个任务。

Tasks 用于并发调度协程,通过 asyncio.create_task(协程对象) 的方式创建Task对象,这样可以让协程加入事件循环中等待被调度执行。除了使用 asyncio.create_task() 函数以外,还可以用低层级的 loop.create_task() 或 ensure_future() 函数。不建议手动实例化 Task 对象。

本质上是将协程对象封装成task对象,并将协程立即加入事件循环,同时追踪协程的状态。

注意:asyncio.create_task() 函数在 Python 3.7 中被加入。在 Python 3.7 之前,可以改用低层级的 asyncio.ensure_future() 函数

示例1:

import asyncioasync def func():print(1)await asyncio.sleep(2)print(2)return "返回值"async def main():print("main开始")# 创建协程,将协程封装到一个Task对象中并立即添加到事件循环的任务列表中,等待事件循环去执行(默认是就绪状态)。task1 = asyncio.create_task(func())# 创建协程,将协程封装到一个Task对象中并立即添加到事件循环的任务列表中,等待事件循环去执行(默认是就绪状态)。task2 = asyncio.create_task(func())print("main结束")# 当执行某协程遇到IO操作时,会自动化切换执行其他任务。# 此处的await是等待相对应的协程全都执行完毕并获取结果ret1 = await task1ret2 = await task2print(ret1, ret2)asyncio.run(main())"""
结果:main开始
main结束
1
1
2
2
返回值 返回值
"""

示例2(简化示例1):

import asyncioasync def func():print(1)await asyncio.sleep(2)print(2)return "返回值"async def main():print("main开始")# 创建协程,将协程封装到Task对象中并添加到事件循环的任务列表中,等待事件循环去执行(默认是就绪状态)。# 在调用task_list = [asyncio.create_task(func(), name="n1"),asyncio.create_task(func(), name="n2")]print("main结束")# 当执行某协程遇到IO操作时,会自动化切换执行其他任务。# 此处的await是等待所有协程执行完毕,并将所有协程的返回值保存到done# 如果设置了timeout值,则意味着此处最多等待的秒,完成的协程返回值写入到done中,未完成则写到pending中。done, pending = await asyncio.wait(task_list, timeout=None)print(done, pending)asyncio.run(main())"""
结果:main开始
main结束
1
1
2
2
{<Task finished name='n1' coro=<func() done, defined at D:\coding\tronado_test\03_tasks.py:31> result='返回值'>, <Task finished name='n2' coro=<func() done, defined at D:\coding\tronado_test\03_tasks.py:31> result='返回值'>} set()
"""

示例3:

import asyncioasync def func():print("执行协程函数内部代码")# 遇到IO操作挂起当前协程(任务),等IO操作完成之后再继续往下执行。当前协程挂起时,事件循环可以去执行其他协程(任务)。response = await asyncio.sleep(2)print("IO请求结束,结果为:", response)# 错误:coroutine_list = [ asyncio.create_task(func()), asyncio.create_task(func()) ]
# 此处不能直接 asyncio.create_task,因为将Task立即加入到事件循环的任务列表,但此时事件循环还未创建,所以会报错。
# 所以可以将协程对象添加致列表来使用。
coroutine_list = [func(),func()
]# 使用asyncio.wait将列表封装为一个协程,并调用asyncio.run实现执行两个协程
# asyncio.wait内部会对列表中的每个协程执行ensure_future,封装为Task对象。
done,pending = asyncio.run( asyncio.wait(coroutine_list) )"""
结果:
执行协程函数内部代码
执行协程函数内部代码
IO请求结束,结果为: None
IO请求结束,结果为: None
"""

2.2.3 async Future对象

A Futureis a special low-level awaitable object that represents an eventual result of an asynchronous operation.

future是一个特殊的低层次可等待对象,它表示异步操作的最终结果。.

Task继承Future, Task对象内部await结果的处理基于Future对象来的。

asyncio中的Future对象是一个相对更偏向底层的可对象,通常我们不会直接用到这个对象,而是直接使用Task对象来完成任务的并和状态的追踪。( Task 是 Futrue的子类 )

Future为我们提供了异步编程中的 最终结果 的处理(Task类也具备状态处理的功能)。

示例1:

import asyncioasync def main():# 获取当前事件循环loop = asyncio.get_running_loop()# # 创建一个任务(Future对象),这个任务什么都不干。fut = loop.create_future()# 等待任务最终结果(Future对象),没有结果则会一直等下去。await futasyncio.run(main())# 结果: 会一直等待

示例2 :

import asyncioasync def set_after(fut):await asyncio.sleep(2)fut.set_result("666")async def main():# 获取当前事件循环loop = asyncio.get_running_loop()# 创建一个任务(Future对象),没绑定任何行为,则这个任务永远不知道什么时候结束。fut = loop.create_future()# 创建一个任务(Task对象),绑定了set_after函数,函数内部在2s之后,会给fut赋值。# 即手动设置future任务的最终结果,那么fut就可以结束了。await loop.create_task(set_after(fut))# 等待 Future对象获取 最终结果,否则一直等下去data = await futprint(data)asyncio.run(main())# 结果:666

Future对象本身函数进行绑定,所以想要让事件循环获取Future的结果,则需要手动设置。而Task对象继承了Future对象,其实就对Future进行扩展,他可以实现在对应绑定的函数执行完成之后,自动执行set_result,从而实现自动结束。

虽然,平时使用的是Task对象,但对于结果的处理本质是基于Future对象来实现的。

2.3 运行 asyncio 程序

asyncio.run(*coro*, ***, *debug=False*)

  • 执行 coroutine coro 并返回结果。

  • 此函数会运行传入的协程,负责管理 asyncio 事件循环,终结异步生成器,并关闭线程池。

  • 当有其他 asyncio 事件循环在同一线程中运行时,此函数不能被调用。

  • 如果 debugTrue,事件循环将以调试模式运行。

  • 此函数总是会创建一个新的事件循环并在结束时关闭。它应当被用作 asyncio 程序的主入口点,理想情况下应当只被调用一次。

import asyncioasync def main():await asyncio.sleep(1)print('hello')asyncio.run(main())# 结果: hello

2.4 创建任务

asyncio.create_task(coro, *, name=None)

  • coro 协程封装为一个 Task 并调度其执行。返回 Task 对象。

  • name 不为 None,它将使用 Task.set_name() 来设为任务的名称。

  • 该任务会在 get_running_loop() 返回的循环中执行,如果当前线程没有在运行的循环则会引发 RuntimeError

  • 此函数 在 Python 3.7 中被加入。在 Python 3.7 之前,可以改用低层级的 asyncio.ensure_future() 函数。

import asyncioasync def func():print(1)await asyncio.sleep(2)print(2)return "返回值"async def main():print("main开始")# 创建协程,将协程封装到Task对象中并添加到事件循环的任务列表中,等待事件循环去执行(默认是就绪状态)。# 在调用task_list = [asyncio.create_task(func(), name="n1"),asyncio.create_task(func(), name="n2")]print("main结束")# 当执行某协程遇到IO操作时,会自动化切换执行其他任务。# 此处的await是等待所有协程执行完毕,并将所有协程的返回值保存到done# 如果设置了timeout值,则意味着此处最多等待的秒,完成的协程返回值写入到done中,未完成则写到pending中。done, pending = await asyncio.wait(task_list, timeout=None)print(done, pending)asyncio.run(main())"""
结果:main开始
main结束
1
1
2
2
{<Task finished name='n1' coro=<func() done, defined at D:\coding\tronado_test\03_tasks.py:31> result='返回值'>, <Task finished name='n2' coro=<func() done, defined at D:\coding\tronado_test\03_tasks.py:31> result='返回值'>} set()
"""

2.5 休眠

coroutine asyncio.sleep(delay, result=None, *, loop=None)

  • 阻塞 delay 指定的秒数。

  • 如果指定了 result,则当协程完成时将其返回给调用者。

  • sleep() 总是会挂起当前任务,以允许其他任务运行。

  • 将 delay 设为 0 将提供一个经优化的路径以允许其他任务运行。 这可供长期间运行的函数使用以避免在函数调用的全过程中阻塞事件循环。

Deprecated since version 3.8, will be removed in version 3.10: loop 形参。

弃用自3.8版本,3.10版本将被删除: loop形参

以下协程示例运行 5 秒,每秒显示一次当前日期:

import asyncio
import datetimeasync def display_date():loop = asyncio.get_running_loop()end_time = loop.time() + 5.0while True:print(datetime.datetime.now())if (loop.time() + 1.0) >= end_time:breakawait asyncio.sleep(1)asyncio.run(display_date())"""
2021-06-16 09:45:57.199182
2021-06-16 09:45:58.199578
2021-06-16 09:45:59.200463
2021-06-16 09:46:00.200563
2021-06-16 09:46:01.201021
"""

3. 扩展

3.1 concurrent.futures.Future对象

使用 线程池、进程池 实现异步操作时用到的对象

示例:

import time
from concurrent.futures import Future
from concurrent.futures.thread import ThreadPoolExecutor
from concurrent.futures.process import ProcessPoolExecutordef func(value):time.sleep(1)print('------>', value)pool = ThreadPoolExecutor(max_workers=5)# 或 pool = ProcessPoolExecutor(max_workers=5)for i in range(10):fut = pool.submit(func, i)print(fut)"""
结果:
<Future at 0x1f178d68730 state=running>
<Future at 0x1f1790dca00 state=running>
<Future at 0x1f1790dcd60 state=running>
<Future at 0x1f1790f7130 state=running>
<Future at 0x1f1790f74c0 state=running>
<Future at 0x1f1790f7850 state=pending>
<Future at 0x1f1790f7970 state=pending>
<Future at 0x1f1790f7a90 state=pending>
<Future at 0x1f1790f7bb0 state=pending>
<Future at 0x1f1790f7cd0 state=pending>
------>------>  01------> 3------>------>42
------> ------>6 
5
------> ------>------> 87
9
"""

上述两种 future 可能会存在交叉使用的时候,所有在此以作对比。

使用场景:协程的使用必须有第三方库的支持,爬虫使用 asyncIOaiohttp 库支持,可以使用协程来做异步编程,但是在使用有些不支持协程的第三方库的时候,就要使用 进程池、线程池 的方式来实现异步编程。

import time
import asyncio
import concurrent.futuresdef func1():# 某个耗时操作time.sleep(2)return "SB"async def main():loop = asyncio.get_running_loop()# 1. Run in the default loop's executor ( 默认ThreadPoolExecutor )# 第一步:内部会先调用 ThreadPoolExecutor 的 submit 方法去线程池中申请一个线程去执行func1函数,并返回一个concurrent.futures.Future对象# 第二步:调用asyncio.wrap_future将concurrent.futures.Future对象包装为asycio.Future对象。# 因为concurrent.futures.Future对象不支持await语法,所以需要包装为 asycio.Future对象 才能使用。fut = loop.run_in_executor(None, func1)result = await futprint('default thread pool', result)# 2. Run in a custom thread pool:# with concurrent.futures.ThreadPoolExecutor() as pool:#     result = await loop.run_in_executor(#         pool, func1)#     print('custom thread pool', result)# 3. Run in a custom process pool:# with concurrent.futures.ProcessPoolExecutor() as pool:#     result = await loop.run_in_executor(#         pool, func1)#     print('custom process pool', result)asyncio.run(main())# 结果:default thread pool SB

示例2(async + 不支持异步编程的模块):

import asyncio
import requestsasync def download_image(url):# 发送网络请求,下载图片(遇到网络下载图片的IO请求,自动化切换到其他任务)print("开始下载:", url)loop = asyncio.get_event_loop()# requests模块默认不支持异步操作,所以就使用线程池来配合实现了。future = loop.run_in_executor(None, requests.get, url)response = await futureprint('下载完成')# 图片保存到本地文件file_name = url.rsplit('_')[-1]with open(file_name, mode='wb') as file_object:file_object.write(response.content)if __name__ == '__main__':url_list = ['https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg',   'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg',    'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg']tasks = [download_image(url) for url in url_list]loop = asyncio.get_event_loop()loop.run_until_complete(asyncio.wait(tasks))"""
结果:开始下载: https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg
开始下载: https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg
开始下载: https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg
下载完成
下载完成
下载完成
"""

3.2 异步迭代器

什么是异步迭代器

实现了 aiter() 和 anext() 方法的对象。anext 必须返回一个 awaitable 对象。async for 会处理异步迭代器的 anext() 方法所返回的可等待对象,直到其引发一个 StopAsyncIteration 异常。由 PEP 492 引入。

什么是异步可迭代对象?

可在 async for 语句中被使用的对象。必须通过它的 aiter() 方法返回一个 asynchronous iterator。由 PEP 492 引入。

异步迭代器其实没什么太大的作用,只是支持了async for语法而已。

import asyncioclass Reader(object):""" 自定义异步迭代器(同时也是异步可迭代对象) """def __init__(self):self.count = 0async def readline(self):# await asyncio.sleep(1)self.count += 1if self.count == 100:return Nonereturn self.countdef __aiter__(self):return selfasync def __anext__(self):val = await self.readline()if val == None:raise StopAsyncIterationreturn valasync def func():# 创建异步可迭代对象async_iter = Reader()# async for 必须要放在async def函数内,否则语法错误。async for item in async_iter:print(item)asyncio.run(func())

3.3 异步上下文管理器

此种对象通过定义 aenter() 和 aexit() 方法来对 async with 语句中的环境进行控制。由 PEP 492 引入。

import asyncioclass AsyncContextManager:def __init__(self):self.conn = Noneasync def do_something(self):# 异步操作数据库return 666async def __aenter__(self):# 异步链接数据库self.conn = await asyncio.sleep(1)return selfasync def __aexit__(self, exc_type, exc, tb):# 异步关闭数据库链接await asyncio.sleep(1)async def func():async with AsyncContextManager() as f:result = await f.do_something()print(result)asyncio.run(func())# 结果:666

3.4 uvloop

是asyncio 事件循环的替代方案,它的效率高于默认asyncio的事件循环。

安装:

pip install uvloop

在使用前必须添加以下代码:

import asyncio
import uvloop
# 将asyncio的默认事件方案替换为uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())# 编写asyncio的代码,与之前写的代码一致。
# 内部的事件循环自动化会变为uvloop
asyncio.run(...)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/491922.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

能源枯竭?在能源互联网时代不存在!

曹军威清华大学信息技术研究院研究员、副院长北京智中能源互联网研究院首席科学家来源&#xff1a;DeepTech深科技演绎inSite第十一期节目能量路由器离我们还远吗&#xff1f;曹军威演绎inSite演讲视频链接&#xff1a;以下为曹军威老师演讲文字稿&#xff1a;&#xff08;根据…

Django3 --- ASGI

1. 什么是WSGI 1.1 CGI 解释 WSGI 之前应该先说一下什么是 CGI&#xff08;通用网关接口&#xff0c;Common Gateway Interface&#xff0c;CGI&#xff09;&#xff0c;是Web 服务器运行时外部程序的规范 &#xff0c; 是外部扩展应用程序与 Web 服务器交互的一个标准接口。…

itextsharp c# asp.net 生成 pdf 文件

一切的开始必须要有2个dll&#xff0c; 可以通过nuget 包xiazai&#xff0c; 关键字是itextsharp. using iTextSharp.text; using iTextSharp.text.pdf; FileStream fs new FileStream(Server.MapPath("pdf") "\\" "First PDF document6.pdf"…

网络安全:等保2.0落地在即,触发五百亿新增市场

报告数据来源&#xff1a;华创证券、东方财富、东吴证券前 言&#xff1a;据公安部十一局七处处长祝国邦&#xff1a;《网络安全等级保护技术》2.0版本将于5月13日发布。相比等保1.0只针对网络和信息系统&#xff0c;等保2.0把云计算、大数据、物联网等新业态也纳入了监管&…

Django3 --- async

官方文档&#xff1a;https://docs.djangoproject.com/en/3.2/releases/3.0/ Django 3.0 通过提供对作为ASGI应用程序运行的支持&#xff0c;开始了我们使 Django 完全具有异步能力的旅程。 Django 3.1于2020年8月4日发布&#xff01;从3.1版本开始&#xff0c;Django将逐步原…

产业|一文读懂自动驾驶汽车产业链上下游

来源&#xff1a; 亿欧自动驾驶汽车它的产业链上下游已经出现支撑公司&#xff0c;并在逐渐走向成熟。自动驾驶分级标准 关于自动驾驶的分级&#xff0c;主要有SAE&#xff08;美国机动车工程师学会&#xff09;标准和NHTSA&#xff08;国家公路交通安全管理局&#xff09;两个…

【python asyncio 运行报错】:raise RuntimeError(‘There is no current event loop in thread %r‘)

代码&#xff1a; # 执行第一个协程程序 asyncio.run(S.crawl_url())select_date S.select_date() select_keyword S.select_keyword(select_date) # 列表# 第二个协程 loop asyncio.get_event_loop() loop.run_until_complete(asyncio.wait([S.parse_html(url) for url i…

Repository 返回 IQueryable?还是 IEnumerable?

这是一个很有意思的问题&#xff0c;我们一步一步来探讨&#xff0c;首先需要明确两个概念&#xff08;来自 MSDN&#xff09;&#xff1a; IQueryable&#xff1a;提供对未指定数据类型的特定数据源的查询进行计算的功能。IEnumerable&#xff1a;公开枚举数&#xff0c;该枚举…

AI教父杰弗里辛顿:AI反学习可能揭开人类梦境的奥秘

来源&#xff1a;网易智能近日&#xff0c;多伦多大学的教员、谷歌大脑&#xff08;Google Brain&#xff09;研究员杰弗里辛顿&#xff08;Geoffrey Hinton&#xff09;发表了炉边谈话。他讨论了神经网络的起源&#xff0c;以及人工智能有朝一日可能像人类一样推理的可行性和意…

AttributeError: partially initialized module ‘aiohttp‘ has no attribute ‘ClientSession‘ (most...)

AttributeError: partially initialized module ‘aiohttp’ has no attribute ‘ClientSession’ (most likely due to a circular import) 问题描述&#xff1a; AttributeError: partially initialized module ‘aiohttp’ has no attribute ‘ClientSession’ (most likely…

关于线程池ThreadPoolExecutor使用总结

本文引用自: http://blog.chinaunix.net/uid-20577907-id-3519578.html 一、简介 线程池类为 java.util.concurrent.ThreadPoolExecutor&#xff0c;常用构造方法为&#xff1a; ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit uni…

AIoT重磅报告:四大关键助力,AI+IoT重新定义未来的可能性

来源&#xff1a;北京物联网智能技术应用协会,智能巅峰导 读随着科技的不断发展&#xff0c;一些在功能上具有相互补充作用的技术正在不可避免地发生结合——例如&#xff0c;人工智能&#xff08;AI&#xff09;和物联网&#xff08;IoT&#xff09;。在本文中&#xff0c;我…

python---aiohttp库

python—aiohttp库 1. 什么事aiohttp 官方网址&#xff1a;https://docs.aiohttp.org/en/stable/ 用于asyncio和Python的异步HTTP客户端/服务器 2. 安装 pip install aiohttp3. ClientSession() Session封装了一个连接池&#xff08;connector instance&#xff09;&…

关于机器学习实战,那些教科书里学不到的12个“民间智慧”

来源&#xff1a;towardsml机器学习算法被认为能够通过学习数据来弄清楚如何执行重要任务。这意味着数据量越大&#xff0c;这些算法就可以解决更加复杂的问题。然而&#xff0c;开发成功的机器学习应用程序需要一定的“民间技巧”&#xff0c;这在教科书或机器学习入门课程中很…

asp.net winform 实现复制,粘贴,剪切功能

System.Windows.Forms.SendKeys.SendWait("^C");//复制System.Windows.Forms.SendKeys.SendWait("^V");//粘贴 System.Windows.Forms.SendKeys.SendWait("^X");//剪切转载于:https://www.cnblogs.com/ninestart/p/4760801.html

aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected

aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected 问题描述&#xff1a; 使用 aiohttp.ClientSession() 爬取数据时出现错误&#xff1a;aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected。 翻译&#xff1a;aiohttp.client_e…

jsonp模拟获取百度搜索相关词汇

随便写了个jsonp模拟百度搜索相关词汇的小demo&#xff0c;帮助新手理解jsonp的用法。 <!DOCTYPE html><html lang"en"><head><meta charset"UTF-8"><title>模拟百度搜索框</title><style>*{margin: 0;padding:…

亚马逊自动打包机:1机可顶24人

来源&#xff1a;网易科技5月14日据国外媒体报道&#xff0c;电商亚马逊公司正在推出能够自动打包订购商品的机器&#xff0c;从而解放数千名员工。该项目的两名工作人员表示&#xff0c;亚马逊近年来开始在少数几个仓库中增加这项技术&#xff0c;扫描从传送带上下来的货物&am…

Pyinstaller打包Django项目

1. 安装pyinstaller pip install pyinstaller2. 介 绍 PyInstaller读取您编写的 Python 脚本。它会分析您的代码以发现您的脚本需要执行的所有其他模块和库。然后它收集所有这些文件的副本——包括活动的 Python 解释器&#xff01;– 并将它们与您的脚本放在一个文件夹中&am…

活着不易,5G时代终端厂商的路在何方?

来源&#xff1a;物联网智库摘要&#xff1a;站在“浮尸遍地”的通信终端的世界里&#xff0c;各大终端厂商无不面临着同一个来自灵魂的拷问&#xff1a;活着不易&#xff0c;5G时代终端厂商的路在何方&#xff1f;从1G模拟通信时代到4G移动宽带时代&#xff0c;全球手机终端厂…