Python Django 协程报错,进程池、线程池与异步调用、回调机制
一、问题描述
在Django视图函数中,导入 gevent 模块
import gevent
from gevent import monkey; monkey.patch_all()
from gevent.pool import Pool
启动Django报错:
MonkeyPatchWarning: Monkey-patching outside the main native thread. Some APIs will not be available. Expect a KeyError to be printed at shutdown.
from gevent import monkey; monkey.patch_all()
MonkeyPatchWarning: Monkey-patching not on the main thread; threading.main_thread().join() will hang from a greenlet
from gevent import monkey; monkey.patch_all()
原因在于执行这行 monkey.patch_all() 代码时报错了。
既然Django不能使用协程,那我需要使用异步执行,怎么办?
请看下文
二、进程池、线程池与异步调用、回调机制
进程池、线程池使用案例
进程池与线程池使用几乎相同,只是调用模块不同~!!
from concurrent.futures import ProcessPoolExecutor # 进程池模块
from concurrent.futures import ThreadPoolExecutor # 线程池模块
import os, time, random # 下面是以进程池为例, 线程池只是模块改一下即可
def talk(name):
print('name: %s pis%s run' % (name,os.getpid()))
time.sleep(random.randint(1, 3)) if __name__ == '__main__':
pool = ProcessPoolExecutor(4) # 设置线程池大小,默认等于cpu核数
for i in range(10):
pool.submit(talk, '进程%s' % i) # 异步提交(只是提交需要运行的线程不等待) # 作用1:关闭进程池入口不能再提交了 作用2:相当于jion 等待进程池全部运行完毕
pool.shutdown(wait=True)
print('主进程')
异步调用与同步调用
concurrent.futures模块提供了高度封装的异步调用接口
ThreadPoolExecutor:线程池,提供异步调用
ProcessPoolExecutor: 进程池,提供异步调用
同步调用
from concurrent.futures import ProcessPoolExecutor # 进程池模块
import os, time, random # 1、同步调用: 提交完任务后、就原地等待任务执行完毕,拿到结果,再执行下一行代码(导致程序串行执行)
def talk(name):
print('name: %s pis%s run' % (name,os.getpid()))
time.sleep(random.randint(1, 3)) if __name__ == '__main__':
pool = ProcessPoolExecutor(4)
for i in range(10):
pool.submit(talk, '进程%s' % i).result() # 同步迪奥用,result(),相当于join 串行 pool.shutdown(wait=True)
print('主进程')
异步调用
from concurrent.futures import ProcessPoolExecutor # 进程池模块
import os, time, random def talk(name):
print('name: %s pis%s run' % (name,os.getpid()))
time.sleep(random.randint(1, 3)) if __name__ == '__main__':
pool = ProcessPoolExecutor(4)
for i in range(10):
pool.submit(talk, '进程%s' % i) # 异步调用,不需要等待 pool.shutdown(wait=True)
print('主进程')
回调机制
可以为进程池或线程池内的每个进程或线程绑定一个函数,该函数在进程或线程的任务执行完毕后自动触发,并接收任务的返回值当作参数,该函数称为回调函数
#parse_page拿到的是一个future对象obj,需要用obj.result()拿到结果
p.submit(这里异步调用).add_done_callback(方法)
案例:下载解析网页页面
import time
import requests
from concurrent.futures import ThreadPoolExecutor # 线程池模块 def get(url):
print('GET %s' % url)
response = requests.get(url) # 下载页面
time.sleep(3) # 模拟网络延时
return {'url': url, 'content': response.text} # 页面地址和页面内容 def parse(res):
res = res.result() # !取到res结果 【回调函数】带参数需要这样
print('%s res is %s' % (res['url'], len(res['content']))) if __name__ == '__main__':
urls = {
'http://www.baidu.com',
'http://www.360.com',
'http://www.iqiyi.com'
} pool = ThreadPoolExecutor(2)
for i in urls:
pool.submit(get, i).add_done_callback(parse) # 【回调函数】执行完线程后,跟一个函数
本文参考链接:
https://blog.csdn.net/weixin_42329277/article/details/80741589
Python Django 协程报错,进程池、线程池与异步调用、回调机制的更多相关文章
- 协程与concurent.furtrue实现线程池与进程池
1concurent.furtrue实现线程池与进程池 2协程 1concurent.furtrue实现线程池与进程池 实现进程池 #进程池 from concurrent.futures impor ...
- Swoole协程报错 Uncaught Error: Call to undefined function go()
解决方法, 在PHP.ini中开启短名
- concurrent.futures模块 -----进程池 ---线程池 ---回调
concurrent.futures模块提供了高度封装的异步调用接口,它内部有关的两个池 ThreadPoolExecutor:线程池,提供异步调用,其基础就是老版的Pool ProcessPoolE ...
- python并发编程-进程池线程池-协程-I/O模型-04
目录 进程池线程池的使用***** 进程池/线程池的创建和提交回调 验证复用池子里的线程或进程 异步回调机制 通过闭包给回调函数添加额外参数(扩展) 协程*** 概念回顾(协程这里再理一下) 如何实现 ...
- Python进阶(5)_进程与线程之协程、I/O模型
三.协程 3.1协程概念 协程:又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存 ...
- Python 原生协程------asyncio
协程 在python3.5以前,写成的实现都是通过生成器的yield from原理实现的, 这样实现的缺点是代码看起来会很乱,于是3.5版本之后python实现了原生的协程,并且引入了async和aw ...
- python之协程与IO操作
协程 协程,又称微线程,纤程.英文名Coroutine. 协程的概念很早就提出来了,但直到最近几年才在某些语言(如Lua)中得到广泛应用. 子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B ...
- python的协程和_IO操作
协程Coroutine: 协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行. 注意,在一个子程序中中断,去执行其他子程序,不是函数调用,有点 ...
- python 3 协程函数
python 3 协程函数 1:把函数的执行结果封装好__iter__和__next__,即得到一个迭代器 2:与return功能类似,都可以返回值,但不同的是,return只能返回一次值,而yiel ...
随机推荐
- Java面试集合(三)-30道面试题
前言 大家好,我是 Vic,今天给大家带来Java面试集合(三)的概述,希望你们喜欢 三 1.在Java中是否可以含有多个类?答:可以含有多个类,但只有一个是public类,public类的类名与文件 ...
- 03-树2 List Leaves (25 分)
Given a tree, you are supposed to list all the leaves in the order of top down, and left to right. I ...
- Fiddler如何查找登陆的可用cookie用于其他请求?方式一
测试过程中,如果你的请求权限是通过cookie响应而不是通过token获得,那么使用如下设置: 1.进入fiddler抓取: 2.jmeter中使用cookie 直接放进去就好了,一般浏览器cooki ...
- OpenFOAM——平行平板间具有相对运动(库埃特流)
本算例翻译整理自:http://the-foam-house5.webnode.es/products/chapter-1-plane-parallel-plates-case/ 这个算例研究了一个距 ...
- ICEM-带四分之一球体的矩形块
原视频下载地址:https://pan.baidu.com/s/1hsHq9mO 密码: 2iq3
- 【算法编程 C++ Python】根据前序遍历、中序遍历重建二叉树
题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7, ...
- mongodb启动命令与端口设置
一.mongodb安装和配置 1.创建tools目录,用于存放安装包 cd /usr/local mkdir -p tools cd tools 2.下载mongodb包(其它版本请自行下载) wge ...
- 第09组 Alpha冲刺(3/4)
队名:软工9组 组长博客:https://www.cnblogs.com/cmlei/ 作业博客:https://edu.cnblogs.com/campus/fzu/SoftwareEngineer ...
- curl的速度为什么比file_get_contents快以及具体原因
一.背景 大家做项目的时候,不免会看到前辈的代码.博主最近看到前辈有的时候请求外部接口用的是file_get_contents,有的用的是curl.稍微了解这两部分的同学都知道,curl在性 ...
- IDEA启动Springboot时,解决报错java.lang.NoClassDefFoundError: javax/servlet/Filter
如下所示,将spring-boot-starter-tomcat依赖中的<scope>provided</scope>注释掉 <dependency> <gr ...