Python 的 Web 服务器网关接口(WSGI 和 ASGI)

93 阅读2分钟

1. WSGI(Web Server Gateway Interface)

WSGI 是一个用于 Python Web 应用程序和 Web 服务器之间的标准接口,由 PEP 3333 定义。它主要用于同步的 HTTP 请求处理,适用于低并发、IO 密集型的应用程序。

特点:

  • 同步处理:每个请求在一个单独的线程中处理,处理期间其他请求必须等待。
  • 适用场景:适用于传统的 Web 应用程序,如 Django。
  • 典型实现:Gunicorn、uWSGI 和 mod_wsgi。

示例代码:

# wsgi_app.py
def simple_app(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    return [b"Hello, WSGI World!"]

if __name__ == "__main__":
    from wsgiref.simple_server import make_server
    server = make_server('localhost', 8051, simple_app)
    print("Serving on port 8051...")
    server.serve_forever()

2. ASGI(Asynchronous Server Gateway Interface)

ASGI 是 WSGI 的精神续作,旨在为异步 Python Web 服务器、框架和应用之间提供一个标准接口。它支持异步请求处理,能够同时处理多个请求,适合高并发场景。

特点:

  • 异步处理:通过事件循环和协程实现高并发性能。
  • 适用场景:适用于实时 Web 应用程序,如 WebSocket、HTTP2。
  • 典型实现:Daphne、Uvicorn 和 Hypercorn。

示例代码:

# asgi_app.py
import asyncio

async def app(scope, receive, send):
    assert scope['type'] == 'http'
    await send({
        'type': 'http.response.start',
        'status': 200,
        'headers': [(b'content-type', b'text/plain')],
    })
    await send({
        'type': 'http.response.body',
        'body': b'Hello, ASGI World!',
    })

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("asgi_app:app", host="127.0.0.1", port=8000, log_level="info")

3. WSGI 与 ASGI 的比较

  • 性能:ASGI 在处理高并发请求时性能更优。
  • 适用场景:WSGI 适用于传统的 Web 应用程序,ASGI 更适合实时和高并发的应用。
  • 实现方式:WSGI 是同步的,ASGI 是异步的。

总结

  • WSGI:适用于传统的、低并发的 Web 应用程序,如 Django。
  • ASGI:适用于需要高并发处理能力的现代 Web 应用程序,如 WebSocket 和 HTTP2。

选择哪种接口取决于你的应用程序的具体需求和性能要求。