Python Web 闪电服务器 - Uvicorn

1,120 阅读4分钟

一、简介

Uvicorn 是一个快速的 ASGI 服务器,使用了 uvloophttptools

  • uvloop : uvloop 是 Python 内建的 asyncio 事件循环的替代品

  • httptools : nodejs HTTP 解析器的 Python 实现

  • ASGI(Asynchronous Server Gateway Interface)服务器:异步网关协议接口,一个介于网络协议服务和Python应用之间的标准接口,能够处理多种通用的协议类型,包括HTTPHTTP2WebSocket

ASGI 有助于改善 Python Web 框架生态系统,在 IO 密集型任务方面,与 Node 和 Go 具有很强的竞争力。它还提供了对 WSGI 无法处理的 HTTP/2 和 WebSockets 的支持。

二、安装

pip install uvicorn

三、使用

1、使用命令行运行:

新建一个示例文件 example.py:

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, world!',
    })

运行服务器:

uvicorn example:app

2、在应用中直接使用:

import uvicorn

async def app(scope, receive, send):
    ...

if __name__ == "__main__":
    uvicorn.run("example:app", host="127.0.0.1", port=5000, log_level="info")

3、使用Gunicorn运行:

Gunicorn 是成熟的,功能齐全的服务器,Uvicorn 内部包含有 Guicorn 的 workers 类,允许你运行 ASGI 应用程序,这些 workers 继承了所有 Uvicorn 高性能的特点,并且给你使用 Guicorn 来进行进程管理。

这样的话,你可能动态增加或减少进程数量,平滑地重启工作进程,或者升级服务器而无需停机。

在生产环境中,Guicorn 大概是最简单的方式来管理 Uvicorn 了,生产环境部署我们推荐使用 Guicorn 和 Uvicorn 的 worker 类:

gunicorn example:app -w 4 -k uvicorn.workers.UvicornWorker

4、工厂模式

使用--factory 可以使用工厂模式来运行:

def create_app():
    app = ...
    return app

运行:

uvicorn --factory example:create_app

四、ASGI 接口

Uvicorn 使用 ASGI 接口与应用程序交互,接收3个参数:

  • scope - 连接信息

  • receive - 传入消息的通道

  • send - 发送消息的通道

基于函数的应用程序:

async def app(scope, receive, send):
    assert scope['type'] == 'http'
    ...

或者基于实例的应用程序:

class App:
    async def __call__(self, scope, receive, send):
        assert scope['type'] == 'http'
        ...

app = App()

连接信息scope 字段如下:

{
    'type': 'http.request',
    'scheme': 'http',
    'root_path': '',
    'server': ('127.0.0.1', 8000),
    'http_version': '1.1',
    'method': 'GET',
    'path': '/',
    'headers': [
        [b'host', b'127.0.0.1:8000'],
        [b'user-agent', b'curl/7.51.0'],
        [b'accept', b'*/*']
    ]
}

五、配置

应用:

  • APP- 要运行的 ASGI 应用程序,格式为"<module>:<attribute>"

  • --factory- 将其APP视为应用程序工厂

Socket 绑定:

  • --host 主机

  • --port 端口

  • --uds 绑定到 UNIX 域

  • --fd - 从此文件描述符绑定到 socket

开发模式:

  • --reload - 启用自动重新加载。

  • --reload-dir - 指定要监视 python 文件更改的目录。可以多次使用。如果未使用,则默认情况下将监视当前目录中的所有目录。

生产:

  • --workers - 使用多个工作进程

日志记录:

  • --log-config - 配置文件

  • --log-level - 设置日志级别。选项: 'critical', 'error', 'warning', 'info', 'debug', 'trace',默认:'info'

  • --no-access-log - 仅禁用访问日志,而不更改日志级别。

  • --use-colors / --no-use-colors- 启用/禁用日志记录的彩色格式,如果未设置,它将被自动检测。

执行:

  • --loop- 设置事件循环实现。

  • --http - 设置 HTTP 协议实现

  • --ws- 设置 WebSockets 协议实现

  • --ws-max-size - 设置 WebSockets 最大消息大小,以字节为单位。

  • --lifespan- 设置 Lifespan 协议实现。

应用接口:

  • --interface- 选择 ASGI3、ASGI2 或 WSGI 作为应用程序接口。

HTTP:

  • --root-path - 设置 ASGI 的 root_path

  • --proxy-headers/ --no-proxy-headers- 启用/禁用 X-Forwarded-Proto、X-Forwarded-For、X-Forwarded-Port 以填充远程地址信息

  • --forwarded-allow-ips 以逗号分隔的 IP 列表以信任代理标头

HTTPS:

  • --ssl-keyfile - SSL 密钥文件

  • --ssl-keyfile-password - 用于解密 ssl 密钥的密码

  • --ssl-certfile - SSL证书文件

  • --ssl-version - 要使用的 SSL 版本

  • --ssl-cert-reqs - 是否需要客户端证书

  • --ssl-ca-certs - CA 证书文件

  • --ssl-ciphers - 要使用的密码

资源限制:

  • --limit-concurrency - 在发出 HTTP 503 响应之前允许的最大并发连接数或任务数

  • --limit-max-requests - 终止进程前对服务的最大请求数。与进程管理器一起运行时很有用,可防止内存泄漏影响长时间运行的进程

  • --backlog - 在储存中保留的最大连接数

超时:

  • --timeout-keep-alive - 如果在此超时内没有收到新数据,则关闭 Keep-Alive 连接