Skip to main content
 首页 » 编程设计

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

2024年11月01日37powertoolsteam

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 many times over the years, and the problem usually ends up being that WSGI’s single-callable interface just isn’t suitable for more involved Web protocols like WebSocket.

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

Even if we made this callable asynchronous, it still only has a single path to provide a request, so protocols that have multiple incoming events (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 awaitable that lets you send events to the client, and receive, an awaitable which lets you receive events from the client.

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