首页 编程教程正文

在Django的View中使用asyncio的方法

piaodoo 编程教程 2020-02-02 11:54:05 1276 0 python教程

这篇文章主要介绍了在Django的View中使用asyncio的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

起步

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请求中的数据依赖的先后顺序。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:https://www.piaodoo.com/179.html

评论

搜索