在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
0
投稿

猜你喜欢

  • 美化段落文本 1

    2008-05-15 12:24:00
  • asp MD5加密方式使用建议

    2011-03-30 11:17:00
  • php Exception异常处理详解

    2023-05-29 21:51:37
  • mysql 存储过程 使用小结

    2010-10-25 20:02:00
  • python进阶教程之函数对象(函数也是对象)

    2022-08-28 01:06:42
  • Python利用PyQt5制作一个获取网络实时数据NBA数据播报GUI功能

    2021-09-08 18:07:26
  • Python3实现爬取简书首页文章标题和文章链接的方法【测试可用】

    2021-10-08 00:22:10
  • Python生成器常见问题及解决方案

    2023-01-23 19:09:43
  • 手把手教你制作Google Sitemap

    2008-09-04 10:35:00
  • 2行css代码屏蔽网页挂马

    2008-09-29 18:54:00
  • ASP实例:使用ASP生成图片彩色校验码

    2009-01-20 16:27:00
  • 删除PHP数组中的重复元素的实现代码

    2023-06-06 21:19:46
  • 谈谈网页一屏有多大?

    2007-12-21 12:28:00
  • Python常用标准库详解(pickle序列化和JSON序列化)

    2022-04-08 12:50:56
  • 仿DW的图形菜单 DIV+CSS

    2007-08-14 10:07:00
  • 基于循环神经网络(RNN)的古诗生成器

    2023-04-29 13:28:06
  • 开心网上input输入框研究

    2009-03-06 12:52:00
  • 基于Python制作B站视频下载小工具

    2023-11-18 11:58:50
  • python GUI库图形界面开发之PyQt5开发环境配置与基础使用

    2023-11-16 04:45:22
  • ASP日期和时间函数用法详解

    2007-10-13 19:33:00
  • asp之家 网络编程 m.aspxhome.com