一、问题描述

在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. 鱼塘钓鱼(fishing)(信息学奥赛一本通 1373)

    [问题描述] 有N个鱼塘排成一排(N<100),每个鱼塘中有一定数量的鱼,例如:N=5时,如下表: 即:在第1个鱼塘中钓鱼第1分钟内可钓到10条鱼,第2分钟内只能钓到8条鱼,……,第5分钟以后再 ...

  2. 【洛谷】P1032 字串变换

    题目地址:https://www.luogu.org/problemnew/show/P1032 洛谷训练场BFS的训练题呀. “BFS不就是用队列的思想去遍历一切情况嘛.我已经不是小孩子了,我肯定能 ...

  3. Ubuntu 安装MySQL报共享库找不到

    错误信息1: ./mysqld: error : cannot open shared object file: No such file or directory 解决办法:安装改库 # apt-g ...

  4. fillter根据value来匹配字段

    字段对应 let cashBackState = { 'WAIT_FIVE': '满5单可返现', 'FINISHED': '已返现' } filters: { cashBackStateFilter ...

  5. 解析.msh或.cas文件

    代码如下:

  6. Kubernetes Pod 生命周期

    一. Pod Hook Kubernetes 为我们提供了生命周期钩子,就是我们所说的Pod Hook,Pod Hook是由kubelet发起的,当容器中的进程启动前或者容器中的进程终止之前运行.这是 ...

  7. 第07组 Beta冲刺(5/5)

    队名:摇光 队长:杨明哲 组长博客:求戳 作业博客:求再戳 队长:杨明哲 过去两天完成了哪些任务 文字/口头描述:暂时没有. 展示GitHub当日代码/文档签入记录:(组内共用,已询问过助教小姐姐) ...

  8. Multi-Agent Reinforcement Learning Based Frame Sampling for Effective Untrimmed Video Recognition

    Multi-Agent Reinforcement Learning Based Frame Sampling for Effective Untrimmed Video Recognition IC ...

  9. c++ 字符串时间格式转换为时间 判断有效期

    转载:https://www.cnblogs.com/maphc/p/3462952.html #include <iostream> #include <time.h> us ...

  10. 360极速浏览器安装vue-devtools插件

    360极速浏览器扩展程序中心并没有提供vue-devtools插件,因此需要自己安装.本文介绍方法适用于所有Chrome内核浏览器. 本人已将编译后的Chrome插件包上传网盘,需要的可以直接下载使用 ...