在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 ,我們通常會創(chuàng)建個子線程專門處理異步任務。
在 wsgi.py 中創(chuàng)建一個單獨線程并運行事件循環(huán):
import asyncio import threading ... application = get_wsgi_application() # 創(chuàng)建子線程并等待 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 中動態(tài)向里面添加任務了:
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請求中的數據依賴的先后順序。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
pandas.DataFrame 根據條件新建列并賦值的方法
下面小編就為大家分享一篇pandas.DataFrame 根據條件新建列并賦值的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python3.5 Pandas模塊缺失值處理和層次索引實例詳解
這篇文章主要介紹了Python3.5 Pandas模塊缺失值處理和層次索引,結合實例形式詳細分析了Python3.5 Pandas模塊缺失值處理和層次索引的原理、處理方法及相關操作注意事項,需要的朋友可以參考下2019-04-04
PyTorch中model.zero_grad()和optimizer.zero_grad()用法
這篇文章主要介紹了PyTorch中model.zero_grad()和optimizer.zero_grad()用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

