【问题标题】:How to use the power of uvicorn and asgi in django?如何在 django 中使用 uvicorn 和 asgi 的强大功能?
【发布时间】:2022-06-15 18:47:23
【问题描述】:

我实现了一个小型 Django 应用程序 (v4.0.4),其中包含一个 REST API — 用于检索一些数据的 GET 方法。接下来,我想使用 gunicorn+uvicorn 运行该项目,因为我在一篇文章中看到了比正常部署更多的基准性能。所以我决定使用wrk 工具来获得自己的基准。

这是我得到的:

Command Webserver Protocol Result (Req/Sec)
python manage.py runserver 0.0.0.0:8000 Django Default wsgi 13.06
gunicorn bitpin.wsgi:application --bind 0.0.0.0:8000 -w 2 gunicorn wsgi 45.20
gunicorn bitpin.asgi:application --bind 0.0.0.0:8000 -w 2 -k uvicorn.workers.UvicornWorker uvicorn+gunicorn asgi 22.17

但是,上面的结果证明了其他东西!
是因为当我想使用asgi 时我必须使用async 方法来代替我的API 视图吗?如果是这样,我如何将 Django REST API 视图更改为 async 一个? 或者我可能错过了一些配置?


[注意]:

  • 我使用以下命令运行基准测试:

    wrk -t4 -c11 -d20s -H "Authorization: Token xxx" http://127.0.0.1:8000/api/v1/content/
    
  • 值得一提的是,在这次测试中,我使用了两个workersgunicorn,很明显workers越高,性能越好。

【问题讨论】:

  • 如果您在 kubernetes 环境中将其作为启用了 HPA(水平自动缩放)的微服务运行,那么您可以使用 django 默认服务器。 kubernetes 将根据负载保持自动缩放(向上或向下),它将添加或减少 pod(如更多 uvicorn 工作人员),这将是动态的。 gunicorn/uvicorn 工人编号在启动时是固定的,不能即时更改。您很可能在谈论物理服务器,但我想如果其他人面临这种​​困境,我还是会在 k8s 环境中留下我的答案。

标签: django gunicorn wsgi uvicorn asgi


【解决方案1】:

如果你想创建异步rest api,请使用一个异步主函数,你可以从这个函数调用另一个同步函数。

例如: #url.py:

path('Create',views.data_export,name='export_database')

#view.py

async def data_export(request):
  if(request.method == 'POST'):
    if(db_connect):
      system_id=request.POST.get('system_id')
      export_id =request.POST.get('export_id')  
      asyncio.create_task(start(system_id,export_id))

  return HttpResponse("Starting")

async def start(system_id,export_id):
  export_task = sync_to_async(start_export,thread_sensitive=False)
  system_id=str(config['COLLECTION_NAME']+'_'+system_id)
  await export_task(system_id,export_id)

export_task 是一个同步函数。

这就是我使其余 api 异步的方式。

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2020-05-27
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多