gpt4 book ai didi

python - 在 Django 3 ASGI 模式和 WSGI 模式下处理请求有什么区别?

转载 作者:太空宇宙 更新时间:2023-11-04 04:00:24 28 4
gpt4 key购买 nike

Django 3应该很快就会发布,它将能够工作在ASGI模式下。 ASGI 模式似乎使 Django 在处理请求时比在 WSGI 模式下更有效率(如果我相信正确的话,每个时间单位可以处理更多的请求)。它是如何实现的? Django 是不是可以同时处理多个请求,但大多数请求都会等待从数据库中获取数据或其他 IO 操作等事件?

最佳答案

主要区别在于同步与异步性质。同步代码虽然在不同的线程或进程中运行并返回响应但被阻塞。没有用于执行其他操作的触发方法。

异步编程允许在事件循环中推送一段代码。在它执行之前做其他事情,然后在完成后用它做一些事情。这是一种非阻塞和基于事件的方法。

来自docs

What’s wrong with WSGI?

You may ask “why not just upgrade WSGI”? This has been asked manytimes over the years, and the problem usually ends up being thatWSGI’s single-callable interface just isn’t suitable for more involvedWeb protocols like WebSocket.

WSGI applications are a single, synchronous callable that takes arequest and returns a response; this doesn’t allow for long-livedconnections, like you get with long-poll HTTP or WebSocketconnections.

Even if we made this callable asynchronous, it still only has a singlepath to provide a request, so protocols that have multiple incomingevents (like receiving WebSocket frames) can’t trigger this.

How does ASGI work?

ASGI is structured as a single, asynchronous callable. It takes scope,which contains details about the incoming request, send, an awaitablethat lets you send events to the client, and receive, an awaitablewhich lets you receive events from the client.

This not only allows multiple incoming events and outgoing events foreach application, but also allows for a background coroutine so theapplication can do other things (such as listening for events on anexternal trigger, like a Redis queue).

关于python - 在 Django 3 ASGI 模式和 WSGI 模式下处理请求有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58462443/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com