在Django的View中使用asyncio的方法
作者:栖迟於一丘 时间:2022-04-10 13:16:41
起步
Django 是个同步框架,本文并不是 让 Django 变成异步框架。而是对于在一个 view 中需要请求多次 http api 的场景。
一个简单的例子
例子来源于 https://stackoverflow.com/questions/44667242/python-asyncio-in-django-view :
def djangoview(request, language1, language2):
async def main(language1, language2):
loop = asyncio.get_event_loop()
r = sr.Recognizer()
with sr.AudioFile(path.join(os.getcwd(), "audio.wav")) as source:
audio = r.record(source)
def reco_ibm(lang):
return(r.recognize_ibm(audio, key, secret language=lang, show_all=True))
future1 = loop.run_in_executor(None, reco_ibm, str(language1))
future2 = loop.run_in_executor(None, reco_ibm, str(language2))
response1 = await future1
response2 = await future2
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(language1, language2))
loop.close()
return(HttpResponse)
这个例子中,把两个任务放到 asyncio 的 loop 运行,等到两个任务都完成了再返回 HttpResponse 。
在 Django 的 View 中使用 asyncio
现在可以对于上面的例子做一个扩充,让它能更合理被使用。
对于使用 asyncio ,我们通常会创建个子线程专门处理异步任务。
在 wsgi.py 中创建一个单独线程并运行事件循环:
import asyncio
import threading
...
application = get_wsgi_application()
# 创建子线程并等待
thread_loop = asyncio.new_event_loop()
def start_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
t = threading.Thread(target=start_loop, args=(thread_loop,), daemon=True)
t.start()
然后就是在 view 中动态向里面添加任务了:
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
text = await response.text()
return text
def hello(request):
from yeezy_bot.wsgi import thread_loop
fut1 = asyncio.run_coroutine_threadsafe(fetch(url1), thread_loop)
fut2 = asyncio.run_coroutine_threadsafe(fetch(url2), thread_loop)
ret1 = fut1.result()
ret2 = fut2.result()
return HttpResponse('')
asyncio.run_coroutine_threadsafe() 返回是 Future 对象,因此可以通过 fut.result() 获得任务的运行结果。 这个方式也可以处理API请求中的数据依赖的先后顺序。
来源:http://www.hongweipeng.com/index.php/archives/1814/
标签:Django,View,asyncio


猜你喜欢
ORACLE8的分区管理
2023-07-13 14:42:43
Python3 伪装浏览器的方法示例
2023-11-16 21:53:44

vue3中7种路由守卫的使用大全举例
2024-05-29 22:43:52
jquery动态遍历Json对象的属性和值的方法
2024-06-09 00:53:36
Vue+ElementUI实现表单动态渲染、可视化配置的方法
2024-04-27 15:56:15

ASP实现全站的301跳转
2010-03-27 21:45:00
python列表详情
2023-12-29 01:59:06
Python面向对象之静态属性、类方法与静态方法分析
2021-03-28 15:14:22
ThinkPHP基于think-queue的队列插件实现消息推送
2023-05-25 05:59:12
如何实现对整个站点所有页面的操作?
2010-05-19 21:20:00
用Python采集《雪中悍刀行》弹幕做成词云实例
2021-05-04 15:24:28

MySQL安装starting the server失败的2种解决办法(推荐!)
2024-01-28 11:16:09

tensorflow实现训练变量checkpoint的保存与读取
2023-12-15 18:10:33

python实现简单文件读写函数
2023-08-29 04:37:24
学习python需要有编程基础吗
2022-05-01 15:23:47
总结一些你可能不知道的ip地址
2022-11-30 15:15:58

asp随机提取access数据库记录的几种方法
2007-09-06 19:42:00
mysql 8.0.22压缩包完整安装与配置教程图解(亲测安装有效)
2024-01-25 05:26:14

Python 实现数组相减示例
2021-08-19 07:01:52
关于pycharm找不到MySQLdb模块的解决方法
2024-01-13 01:51:20
