一、问题描述

在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 协程报错,进程池、线程池与异步调用、回调机制的更多相关文章

  1. 协程与concurent.furtrue实现线程池与进程池

    1concurent.furtrue实现线程池与进程池 2协程 1concurent.furtrue实现线程池与进程池 实现进程池 #进程池 from concurrent.futures impor ...

  2. Swoole协程报错 Uncaught Error: Call to undefined function go()

    解决方法, 在PHP.ini中开启短名

  3. concurrent.futures模块 -----进程池 ---线程池 ---回调

    concurrent.futures模块提供了高度封装的异步调用接口,它内部有关的两个池 ThreadPoolExecutor:线程池,提供异步调用,其基础就是老版的Pool ProcessPoolE ...

  4. python并发编程-进程池线程池-协程-I/O模型-04

    目录 进程池线程池的使用***** 进程池/线程池的创建和提交回调 验证复用池子里的线程或进程 异步回调机制 通过闭包给回调函数添加额外参数(扩展) 协程*** 概念回顾(协程这里再理一下) 如何实现 ...

  5. Python进阶(5)_进程与线程之协程、I/O模型

    三.协程 3.1协程概念 协程:又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存 ...

  6. Python 原生协程------asyncio

    协程 在python3.5以前,写成的实现都是通过生成器的yield from原理实现的, 这样实现的缺点是代码看起来会很乱,于是3.5版本之后python实现了原生的协程,并且引入了async和aw ...

  7. python之协程与IO操作

    协程 协程,又称微线程,纤程.英文名Coroutine. 协程的概念很早就提出来了,但直到最近几年才在某些语言(如Lua)中得到广泛应用. 子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B ...

  8. python的协程和_IO操作

    协程Coroutine: 协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行. 注意,在一个子程序中中断,去执行其他子程序,不是函数调用,有点 ...

  9. python 3 协程函数

    python 3 协程函数 1:把函数的执行结果封装好__iter__和__next__,即得到一个迭代器 2:与return功能类似,都可以返回值,但不同的是,return只能返回一次值,而yiel ...

随机推荐

  1. gulp/webpack运行sass报错解决方法

    帮同事安装gulp和webpack运行环境,使用cnpm install安装node-sass之后,运行项目总是报错,提示vendor目录不存在,几番百度之后,找到处理方法,这里记录一笔,防止以后遇到 ...

  2. vue-element-admin 实现动态路由(从后台查询出菜单列表绑定)

    1. 在路由实例中保留基础路由 router/index.js中只需要保留基础路由,其他的都删了 2. 获取用户菜单,并保存到Vuex中 stroe/modules/user.js中,有个getInf ...

  3. ES6 数组方法 forEach map filter find every some reduce

    1. forEach const colors = ['red', 'blue', 'green'] colors.forEach(function (params) { console.log(pa ...

  4. php . extension_loaded

    (PHP 4, PHP 5, PHP 7) extension_loaded — 检查一个扩展是否已经加载 如果 name 指定的扩展已加载,返回TRUE,否则返回 FALSE. Example #1 ...

  5. mapreduce中reduce没有执行

    hadoop执行mapreduce过程reduce不执行原因 1.如果你的map过程中没有context.write()是不执行reduce过程的:2.如果你的map过程中context.write( ...

  6. CF1221F Choose a Square(二维偏序)

    由于y=x,我们可以将点对称过来,以便(x,y)(x<y) 考虑选取正方形(a,a,b,b),点集则为\((a\le x\le y\le b)\),相当于二维数点 将点按x降序,y升序排列,线段 ...

  7. CentOS7 通过systemd 添加开机重启服务

    现在越来越多的环境采用 CentOS 7 作为基础配置,特别是 Hadoop生态 如果要测试或部署环境需要启动很多组件(zookeeper.kafka.redis等等),如下内容是在操作系统层实现开机 ...

  8. Java自己实现HTTP服务器来理解GET和POST区别

    GET请求和POST请求有什么区别?GET请求的参数在URL的问号后面显示,而POST参数不在URL上:POST可以比GET请求更大的数据…一般的回答都是这样.   但是作为一个高端大气上档次的程序员 ...

  9. linux学习(1):linux命令大全

    Linux命令 目录 1       文件管理... 5 1.1          basename. 5 1.2          cat 5 1.3          cd. 5 1.4      ...

  10. tensorflow运行时openssl与boringssl兼容性问题

    tensorflow中,grpc使用boringssl进行加密,boringssl是google基于openssl自行开发的一条分支,有许多相同函数,但底层实现以及支持的加密类型有不同. 且tenso ...