问题:
    https://stackoverflow.com/questions/73968556/how-to-send-mail-asynchronously-using-djangos-async-view
    https://blog.csdn.net/weixin_42134789/article/details/108613214

    如下时最好的方式,且使用asgi启动

    1. import asyncio
    2. import datetime
    3. import aiohttp
    4. import httpx as httpx
    5. from django.http import HttpResponse
    6. import requests
    7. from asgiref.sync import sync_to_async
    8. async def async_print():
    9. # async with httpx.AsyncClient() as client:
    10. # r = await client.get("http://43.143.221.44:9999/")
    11. # print(r)
    12. async with aiohttp.ClientSession() as client:
    13. r = await client.get("http://43.143.221.44:9999/")
    14. async def index(request):
    15. asyncio.create_task(async_print())
    16. return HttpResponse(datetime.datetime.now())

    重点,执行同步任务时,使用sync_to_async、thread_sensitive=Falses时也可以不使用asgi中间件

    1. async def async_print():
    2. await sync_to_async(subprocess.run, thread_sensitive=False)('httpx -u https://www.baidu.com/')
    3. async def index(request):
    4. asyncio.create_task(async_print())
    5. return HttpResponse(datetime.datetime.now())

    如何使用 Uvicorn 托管 Django
    https://docs.djangoproject.com/zh-hans/4.1/howto/deployment/asgi/uvicorn/

    1. uvicorn quickstart.asgi:application --reload

    在开发环境可以使用热加载 —relaod

    基于类的视图

    1. from django.views import View
    2. class AsyncView(View):
    3. async def get(self, request, *args, **kwargs):
    4. asyncio.create_task(async_print())
    5. return HttpResponse("Hello async world!")

    https://docs.djangoproject.com/zh-hans/4.1/topics/class-based-views/#async-class-based-views