问题:
https://stackoverflow.com/questions/73968556/how-to-send-mail-asynchronously-using-djangos-async-view
https://blog.csdn.net/weixin_42134789/article/details/108613214
如下时最好的方式,且使用asgi启动
import asyncio
import datetime
import aiohttp
import httpx as httpx
from django.http import HttpResponse
import requests
from asgiref.sync import sync_to_async
async def async_print():
# async with httpx.AsyncClient() as client:
# r = await client.get("http://43.143.221.44:9999/")
# print(r)
async with aiohttp.ClientSession() as client:
r = await client.get("http://43.143.221.44:9999/")
async def index(request):
asyncio.create_task(async_print())
return HttpResponse(datetime.datetime.now())
重点,执行同步任务时,使用sync_to_async、thread_sensitive=Falses时也可以不使用asgi中间件
async def async_print():
await sync_to_async(subprocess.run, thread_sensitive=False)('httpx -u https://www.baidu.com/')
async def index(request):
asyncio.create_task(async_print())
return HttpResponse(datetime.datetime.now())
如何使用 Uvicorn 托管 Django
https://docs.djangoproject.com/zh-hans/4.1/howto/deployment/asgi/uvicorn/
uvicorn quickstart.asgi:application --reload
在开发环境可以使用热加载 —relaod
基于类的视图
from django.views import View
class AsyncView(View):
async def get(self, request, *args, **kwargs):
asyncio.create_task(async_print())
return HttpResponse("Hello async world!")
https://docs.djangoproject.com/zh-hans/4.1/topics/class-based-views/#async-class-based-views