问题描述
我正在尝试使用async
async
Django3.1
功能
# urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('api/',views.api),path('api/aggregated/',views.api_aggregated),path('api/aggregated_sync/',views.api_aggregated_sync),]
# views.py
import time
import httpx
import asyncio
from django.http import JsonResponse
from django.urls import path
async def api(request):
await asyncio.sleep(1)
payload = {"message": "Hello World"}
if "task_id" in request.GET:
payload["task_id"] = request.GET["task_id"]
return JsonResponse(payload)
def get_api_urls(num=10):
base_url = "http://127.0.0.1:9006/api/"
return [
f"{base_url}?task_id={task_id}" for task_id in range(num)
]
async def api_aggregated(request):
s = time.perf_counter()
responses = []
urls = get_api_urls(num=10)
async with httpx.AsyncClient() as client:
responses = await asyncio.gather(*[
client.get(url) for url in urls
])
responses = [r.json() for r in responses]
elapsed = time.perf_counter() - s
result = {
"message": "Hello Async World","responses": responses,"debug_message": f"fecth executed in {elapsed:0.2f} seconds.",}
return JsonResponse(result)
def api_aggregated_sync(request):
s = time.perf_counter()
responses = []
urls = get_api_urls(num=10)
for url in urls:
r = httpx.get(url)
responses.append(r.json())
elapsed = time.perf_counter() - s
result = {
"message": "Hello Sync World!","aggregated_responses": responses,"debug_message": f"fetch executed in {elapsed:0.2f} seconds.",}
return JsonResponse(result)
我尝试过asgi
服务器uvicorn
并从命令开始:
uvicorn --workers 10 --reload myproject.asgi:application --port 9006
但是当我去api/aggregated_sync/
时,总是会给我一个ReadTimeout
的错误:
timeout=timeout.as_dict(),File "/usr/local/python3.6.8/lib/python3.6/contextlib.py",line 99,in __exit__
self.gen.throw(type,value,traceback)
File "/home/jiamin/venv_async_django/lib/python3.6/site-packages/httpx/_exceptions.py",line 359,in map_exceptions
raise mapped_exc(message,**kwargs) from exc # type: ignore
httpx.ReadTimeout: timed out
如何解决此错误?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)