在Django的View中使用asyncio的方法

yipeiwu_com5年前Python基础

起步

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现移位加密和解密

python实现移位加密和解密

本文实例为大家分享了python实现移位加密和解密的具体代码,供大家参考,具体内容如下 代码很简单,就不多做解释啦。主要思路是将字符串转为Ascii码,将大小写字母分别移位密钥表示的位...

matplotlib绘制符合论文要求的图片实例(必看篇)

matplotlib绘制符合论文要求的图片实例(必看篇)

最近需要将实验数据画图出来,由于使用python进行实验,自然使用到了matplotlib来作图。 下面的代码可以作为画图的模板代码,代码中有详细注释,可根据需要进行更改。 # -*...

python中文乱码的解决方法

乱码原因: 源码文件的编码格式为utf-8,但是window的本地默认编码是gbk,所以在控制台直接打印utf-8的字符串当然是乱码了! 解决方法: 1、print mystr.deco...

栈和队列数据结构的基本概念及其相关的Python实现

先来回顾一下栈和队列的基本概念: 相同点:从"数据结构"的角度看,它们都是线性结构,即数据元素之间的关系相同。 不同点:栈(Stack)是限定只能在表的一端进行插入和删除操作的线性表。...

对python中GUI,Label和Button的实例详解

如下所示: #coding=utf-8 import Tkinter top=Tkinter.Tk() #400x300:代表初始化时主窗口的大小,300,100分别代表窗口的初始...