单线程+异步协程

一 . 线程池和进程池

  可以适当的使用,在大量的IO情况下有更好的方法

import time
from multiprocessing.dummy import Pool
def request(url):print('正在下载->',url)time.sleep(2)print('下载完毕->',url)
start = time.time()
urls = ['www.baidu.com','www.taobao.com','www.sougou.com'
]
pool = Pool(3)
pool.map(request,urls)print('总耗时->',time.time()-start)

二 . 单线程+异步协程(高性能的异步爬虫)

event_loop:相当于无线循环,我们可以把特殊的函数注册到这个时间循环上,异步执行
coroutine:协程,就是被async修饰的函数
task:任务,它是对协程进一步封装,包含了协程的各个状态
future:将要执行的任务
async/await,这两个是需要重点了解的

  事件循环

import asyncio
async def hello(name):print('hello->'+ name)
# 获取一个协程对象
c = hello('attila')# 创建一个事件循环
loop = asyncio.get_event_loop()# 将协程对象注册到事件循环中,并且启动事件循环对象
loop.run_until_complete(c)

  task

import asyncio
async def hello(name):print('hello->'+ name)
# 获取一个协程对象
c = hello('attila')# 创建一个事件循环
loop = asyncio.get_event_loop()# 把协程封装到task中
task = loop.create_task(c)
print(task)  # Task pending
# 将协程对象注册到事件循环中,并且启动事件循环对象
loop.run_until_complete(task)
print(task)  # Task finished

  future

import asyncio
async def hello(name):print('hello->'+ name)
# 获取一个协程对象
c = hello('attila')# 把协程封装到task中
task = asyncio.ensure_future(c)# 将协程对象注册到事件循环中,并且启动事件循环对象
loop.run_until_complete(task)

  绑定回调

import asynciodef call_back(task):print('---->',task.result())
async def hello(name):print('hello->'+ name)return name
# 获取一个协程对象
c = hello('attila')# 把协程封装到task中
task = asyncio.ensure_future(c)
# 给任务绑定一个回调函数,这个call_back里面的参数就是绑定回到函数的task
task.add_done_callback(call_back)
# 将协程对象注册到事件循环中,并且启动事件循环对象
loop.run_until_complete(task)

  多任务异步协程(这里需要用到一个新模块aiohttp,一定不能是requests,因为requests是一个非异步模块)

    pip install aiohttp

import aiohttp
import asyncioasync def get_page(url):async with aiohttp.ClientSession() as session:async with await session.get(url=url) as response:  # 只要有io操作的地方就要挂起(await)page_text = await response.text()print(page_text)start = time.time()
# 这里的url是自己在后台搭建的服务器,没给url都是time.sleep(2)
urls = ['http://127.0.0.1:5000/cat','http://127.0.0.1:5000/dog','http://127.0.0.1:5000/monkey','http://127.0.0.1:5000/cat','http://127.0.0.1:5000/dog','http://127.0.0.1:5000/monkey','http://127.0.0.1:5000/cat','http://127.0.0.1:5000/dog','http://127.0.0.1:5000/monkey',
]
tasks = []
loop = asyncio.get_event_loop()
for url in urls:c = get_page(url)task = asyncio.ensure_future(c)tasks.append(task)
loop.run_until_complete(asyncio.wait(tasks))
print('总耗时->',time.time()-start)   # 总耗时-> 2.053046464920044

 

  

 

转载于:https://www.cnblogs.com/attila/p/10913429.html

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

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

相关文章

Repeater\DataList\GridView实现分页,数据编辑与删除

一、实现效果 1、GridView 2、DataList 3、Repeater 二、代码 1、可以去Csdn资源下载,包含了Norwind中文示例数据库噢!(放心下,不要资源分) 下载地址:数据控件示例源码Norwind中文数据库 2、我的开发环境&a…

网站快速成型_我的老板对快速成型有什么期望?

网站快速成型Some of the top excuses I have gotten from clients when inviting them into a prototyping session are: “I am not a designer!” “I can’t draw!” “I have no creative background!”在邀请客户参加原型制作会议时,我从客户那里得到的一些主…

碎片化学前端,融入到积极上进的环境,我推荐~

众所周知,关注公众号可以了解学习掌握技术方向,学习优质好文,落实到自己项目中。还可以结交圈内好友,让自己融入到积极上进的技术氛围,促进自己的技术提升。话不多说,推荐这些优质前端公众号前端之神 80w阅…

重学JavaScript深入理解系列(六)

JavaScript深入理解—-闭包(Closures) 概要 本文将介绍一个在JavaScript经常会拿来讨论的话题 —— 闭包(closure)。闭包其实已经是个老生常谈的话题了; 有大量文章都介绍过闭包的内容,尽管如此,这里还是要试着从理论角…

EXT.NET复杂布局(四)——系统首页设计(上)

很久没有发帖了,很是惭愧,因此给各位使用EXT.NET的朋友献上一份礼物。 本篇主要讲述页面设计与效果,下篇将讲述编码并提供源码下载。 系统首页设计往往是个难点,因为往往要考虑以下因素: 重要通知系统功能菜单快捷操作…

figma设计_在Figma中使用隔片移交设计

figma设计I was quite surprised by how much the design community resonated with the concept of spacers since I published my 自从我发表论文以来,设计界对间隔件的概念产生了多少共鸣,我感到非常惊讶。 last story. It encouraged me to think m…

axios源码中的10多个工具函数,值得一学~

大家好,我是若川。最近组织了源码共读活动,感兴趣的可以点此加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步。同时极力推荐订阅我写的《学习源码整体架构系列》 包含20余篇源码文章。本文来自读者Ethan01投稿…

安装jenkins时出现 No such plugin: cloudbees-folder的解决办法

今天安装了一下jenkins,在初始化安装插件时出现“ No such plugin: cloudbees-folder”错误,根据网上的教程: 1、打开链接“http://ftp.icm.edu.pl/packages/jenkins/plugins/cloudbees-folder/”,在最下面找到并打开“latest”目…

寄充气娃娃怎么寄_我如何在5小时内寄出新设计作品集

寄充气娃娃怎么寄Over the Easter break, I challenged myself to set aside an evening rethinking the structure, content and design of my portfolio in Notion with a focus on its 在复活节假期,我挑战自己,把一个晚上放在一边,重新思…

基于Hbase的用户评分协同过滤推荐算法

基于Hbase的用户评分协同过滤推荐算法 作者: 张保维 2012-1-3 一、 概述 本文为推荐引擎设计的基础篇,介绍基于hbase 存储方式用户评分的方式进行推荐的主体算法及在分布式平台环境下的实现。由于推荐算法分支众多,我们先从简单及实用的算法…

最全 JavaScript Array 方法 详解

大家好,我是若川。最近组织了源码共读活动,感兴趣的可以点此加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步。同时极力推荐订阅我写的《学习源码整体架构系列》 包含20余篇源码文章。我们在日常开发中&#…

[译] React Hooks: 没有魔法,只是数组

[译] React Hooks: 没有魔法,只是数组 原文链接: medium.com/ryardley/r… 我是 React 新特性 Hooks 的粉丝。但是,在你使用 React Hooks的过程中,有一些看上去 很奇怪的限制 。在本文里,对于那些还在为了理解这些限制…

管理沟通中移情的应用_移情在设计中的重要性

管理沟通中移情的应用One of the most important aspects of any great design is the empathetic understanding of and connection to the user. If a design is ‘selfish’, as in when a product designed with the designer in mind and not the user, it will ultimatel…

网易前端进阶特训营,邀你免费入营!一举解决面试晋升难题!

网易等大厂的前端岗位一直紧缺,特别是资深级。最近一位小哥面进网易,定级P4(资深),总包60W,给大家带来真实面经要点分享。网易的要求有:1.对性能优化有较好理解,熟悉常用调试工具2.熟…

Feign的构建过程及自定义扩展功能

spring-cloud-openfeign-core-2.1.1.RELEASE.jar 中 HystrixFeign 的详细构建过程: EnableFeignClients -> FeignClientsRegistrar 扫描 Feign注解的类 -> FeignClientFactoryBean通过Targeter生产FeignClient -> Targeter通过Feign.Builder构建Feign ->…

angelica类似_亲爱的当归(Angelica)是第一个让我哭泣的VR体验

angelica类似It was a night just like any other night. I finished work for the day and closed my laptop. I had dinner and after an hour, I put on my Oculus Quest headset in order to begin my VR workout.就像其他任何夜晚一样, 这 是一个夜晚。 我完成…

面试官:请手写一个带取消功能的延迟函数,axios 取消功能的原理是什么

大家好,我是若川。最近组织了源码共读活动,感兴趣的可以点此加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步。同时极力推荐订阅我写的《学习源码整体架构系列》 包含20余篇源码文章。本文仓库 https://githu…

关于base64编码的原理及实现

我们的图片大部分都是可以转换成base64编码的data:image。 这个在将canvas保存为img的时候尤其有用。虽然除ie外,大部分现代浏览器都已经支持原生的基于base64的encode和decode,例如btoa和atob。(将canvas画布保存成img并强制改变…

Django web开发系列(五)模板

一 前言在上一节了解到视图函数处理后,会将结果渲染到创建的html页面,但html如何接收并显示视图函数返回的动态数据呢?最常用的做法就是使用模板(Template),本节将简单介绍一下模板的作用和用法。 可以这样简单的理解模板的概念&a…

facebook 面试_如何为您的Facebook产品设计面试做准备

facebook 面试重点 (Top highlight)Last month, I joined Facebook to work on Instagram DMs and as a way to pay it forward, I 上个月,我加入了Facebook,从事Instagram DM的工作,作为一种支付方式,我 offered to help anyone…