Python并发请求之requests_future模块使用
# -*- coding: utf-8 -*-
# @Time : 2019-12-09 10:00
# @Author : cxa
# @File : demo.py
# @Software: PyCharm
from requests_futures.sessions import FuturesSession
from concurrent.futures import as_completed
from lxml import html
import time
url = ["http://www.baidu.com", "http://www.163.com", "http://www.google.com", "http://www.cnblogs.com/c-x-a"]
def get_node(source, x=".//head/title//text()"):
root = html.fromstring(source)
node = root.xpath(x)
return node
def response_hook(resp, *args, **kwargs):
start = time.time()
resp.encoding = resp.apparent_encoding
resp.data = resp.text
resp.code = resp.status_code
resp.headers = resp.headers
resp.elapsed = time.time() - start
def get_req():
with FuturesSession(max_workers=4) as session:
futures = [session.get(i, hooks={"response": response_hook}) for i in url]
for future in as_completed(futures):
resp = future.result()
print("状态码", resp.code)
print("标题", get_node(resp.data)[0])
print("耗时", resp.elapsed)
print("="*30)
if __name__ == '__main__':
get_req()
修改之后
from requests_futures.sessions import FuturesSession
from concurrent.futures import as_completed
from lxml import html
import time
url = ["http://www.baidu.com", "http://www.163.com", "http://www.google.com", "http://www.cnblogs.com/c-x-a"]
class MySession(FuturesSession):
def request(self, method, url, hooks=None, *args, **kwargs):
start = time.time()
if hooks is None:
hooks = {}
def response_hook(resp, *args, **kwargs):
resp.encoding = resp.apparent_encoding
resp.data = resp.text
resp.code = resp.status_code
resp.headers = resp.headers
resp.elapsed = time.time() - start
try:
if isinstance(hooks['response'], (list, tuple)):
hooks['response'].insert(0, response_hook)
else:
hooks['response'] = [response_hook, hooks['response']]
except KeyError:
hooks['response'] = response_hook
return super(MySession, self).request(method, url, hooks=hooks, *args, **kwargs)
def get_node(source, x=".//head/title//text()"):
root = html.fromstring(source)
node = root.xpath(x)
return node
def get_req():
with MySession(max_workers=4) as session:
futures = [session.get(i) for i in url]
for future in as_completed(futures):
resp = future.result()
print("状态码", resp.code)
print("标题", get_node(resp.data)[0])
print("耗时", resp.elapsed)
print("=" * 30)
if __name__ == '__main__':
get_req()
Python并发请求之requests_future模块使用的更多相关文章
- Python并发复习2 - 多线程模块threading
一.多线程的调用 threading 模块建立在thread 模块之上.thread模块以低级.原始的方式来处理和控制线程,而threading 模块通过对thread进行二次封装, 提供了更方便的a ...
- Python并发复习4- concurrent.futures模块(线程池和进程池)
Python标准库为我们提供了threading(多线程模块)和multiprocessing(多进程模块).从Python3.2开始,标准库为我们提供了concurrent.futures模块,它提 ...
- Python并发复习3 - 多进程模块 multiprocessing
python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程.Python提供了非常好用的多进程包multiprocessing,只需要定 ...
- python 并发编程 基于gevent模块 协程池 实现并发的套接字通信
基于协程池 实现并发的套接字通信 客户端: from socket import * client = socket(AF_INET, SOCK_STREAM) client.connect(('12 ...
- python 并发编程 基于gevent模块实现并发的套接字通信
之前线程池是通过操作系统切换线程,现在是程序自己控制,比操作系统切换效率要高 服务端 from gevent import monkey;monkey.patch_all() import geven ...
- Python并发复习1 - 多线程
一.基本概念 程序: 指令集,静态, 进程: 当程序运行时,会创建进程,是操作系统资源分配的基本单位 线程: 进程的基本执行单元,每个进程至少包含一个线程,是任务调度和执行的基本单位 > 进程和 ...
- python 并发编程 协程 目录
python 并发编程 协程 协程介绍 python 并发编程 协程 greenlet模块 python 并发编程 协程 gevent模块 python 并发编程 基于gevent模块实现并发的套接字 ...
- python网页请求urllib2模块简单封装代码
这篇文章主要分享一个python网页请求模块urllib2模块的简单封装代码. 原文转自:http://www.jbxue.com/article/16585.html 对python网页请求模块ur ...
- python web中的并发请求
python web可以选择django,也可以选择flask,它们的原理差不多.flask比较轻量,下面写一段flask程序来说明python web对并发请求的处理. app.py import ...
随机推荐
- python基础05day--函数
一 函数知识体系 什么是函数?为什么要用函数?函数的分类:内置函数与自定义函数如何自定义函数 语法 定义有参数函数,及有参函数的应用场景 定义无参数函数,及无参函数的应用场景 定义空函数,及空函数的应 ...
- mybatis关联映射一对多
实际项目中也存在很多的一对多的情况,下面看看这个简单的例子 table.sql CREATE TABLE tb_clazz( id INT PRIMARY KEY AUTO_INCREMENT, CO ...
- Vue学习之vue-resource小结(五)
一.Vue实现数据交互的方式: 1.Vue除了vue-resource之外,还可以使用‘axios’的第三方包实现数据的请求: 2.常见的数据请求类型有: get.post.jsonp 3.JSONP ...
- k8s的pod或者ns资源一直terminating删除办法
假设你要删掉的ns资源,发现一直删不了处于terminating状态 1.首先试一下先把这个ns的所有pod都删掉kubectl delete pod --all -n <terminating ...
- Spring Cloud 手记
文档:https://www.springcloud.cc/spring-cloud-dalston.html#_features 一年了,我们都用 Spring Cloud 干了啥?:https:/ ...
- 软工团队第三次作业——编码组Alpha版本
众志陈成组 柚荐--Alpha版本 编码部分 一.编码思路 思维导图如下 二.下载及操作方法 1.下载地址 GitHub地址:https://github.com/NyimaC/YouSuggest ...
- 如何测试Web服务.3
-->全文字数:2254,需要占用你几分钟的阅读时间 ,您也可以收藏后,时间充足时再阅读- ->第一节讲了<Web服务基础介绍>,第二节讲了<Web服务测试工具> ...
- PAT 乙级 1007.素数对猜想 C++/Java
1007 素数对猜想 (20 分) 题目来源 让我们定义dn为:dn=pn+1−pn,其中pi是第i个素数.显然有d1=1,且对于n>1有dn是偶数.“ ...
- docker学习7-Dockerfile制作自己的镜像文件
前言 如果你是一个python自动化测试人员,某天你在公司终于完成了一个项目的接口自动化脚本工作,在你自己常用的本机或者服务器上调试完成了脚本,稳稳地没问题. 可是晚上下班回家,你自己找了个linux ...
- Java并发编程:ThreadPoolExecutor + Callable + Future(FutureTask) 探知线程的执行状况
如题 (总结要点) 使用ThreadPoolExecutor来创建线程,使用Callable + Future 来执行并探知线程执行情况: V get (long timeout, TimeUnit ...