uvicorn README

The project's README from github.com/Kludex/uvicorn. As one markdown file: README.md.

uvicorn

An ASGI web server, for Python.


Build Status Package version Supported Python Version Discord


Documentation: https://uvicorn.dev

Source Code: https://www.github.com/Kludex/uvicorn


Uvicorn is an ASGI web server implementation for Python.

Until recently Python has lacked a minimal low-level server/application interface for async frameworks. The ASGI specification fills this gap, and means we're now able to start building a common set of tooling usable across all async frameworks.

Uvicorn currently supports HTTP/1.1, HTTP/2 and WebSockets.

Quickstart

Install using pip:

$ pip install uvicorn

This will install uvicorn with minimal (pure Python) dependencies.

$ pip install 'uvicorn[standard]'

This will install uvicorn with "Cython-based" dependencies (where possible) and other "optional extras".

In this context, "Cython-based" means the following:

Moreover, "optional extras" means that:

Create an application, in 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!',
    })

Run the server:

$ uvicorn example:app

Why ASGI?

Most well established Python Web frameworks started out as WSGI-based frameworks.

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, which WSGI doesn't support well.

Having an async concurrency model also allows for options such as lightweight background tasks, and can be less of a limiting factor for endpoints that have long periods being blocked on network I/O such as dealing with slow HTTP requests.


Alternative ASGI servers

A strength of the ASGI protocol is that it decouples the server implementation from the application framework. This allows for an ecosystem of interoperating webservers and application frameworks.

Daphne

The first ASGI server implementation, originally developed to power Django Channels, is the Daphne webserver.

It is run widely in production, and supports HTTP/1.1, HTTP/2, and WebSockets.

Any of the example applications given here can equally well be run using daphne instead.

$ pip install daphne
$ daphne app:App

Hypercorn

Hypercorn was initially part of the Quart web framework, before being separated out into a standalone ASGI server.

Hypercorn supports HTTP/1.1, HTTP/2, and WebSockets.

It also supports the excellent trio async framework, as an alternative to asyncio.

$ pip install hypercorn
$ hypercorn app:App

Mangum

Mangum is an adapter for using ASGI applications with AWS Lambda & API Gateway.

Granian

Granian is an ASGI compatible Rust HTTP server which supports HTTP/2, TLS and WebSockets.


Uvicorn is BSD licensed code.
Designed & crafted with care.

— 🦄 —

uvicorn (Kludex/uvicorn)

Searching Database…

Что это такое?Uvicorn — это ASGI-сервер для Python, то есть асинхронный сервер для запуска веб-приложений и API на Python. Он поддерживает HTTP/1.1, HTTP/2 и WebSockets.
Чем ASGI-сервер отличается от серверов, которые стоят за классическими Python-фреймворками?Классические WSGI-приложения обрабатывают каждый запрос как одно синхронное обращение, поэтому долгоживущие соединения вроде WebSockets или long-poll HTTP им плохо подходят. ASGI работает асинхронно — такие соединения поддерживает, плюс позволяет запускать лёгкие фоновые задачи.
Как запустить своё приложение на этом сервере?Установите пакет через pip, опишите ASGI-приложение в файле, например example.py, и запустите команду uvicorn example:app из терминала.
Мне просто сделать pip install uvicorn или ставить пакет с дополнением [standard]?Обычная установка — это чистый Python с минимумом зависимостей. uvicorn[standard] добавляет ускорения на основе Cython — цикл событий uvloop и httptools для HTTP — а также дополнительные пакеты: websockets, watchfiles для --reload, python-dotenv и PyYAML.
Он будет работать на Windows и macOS или только на Linux?Это обычный pip-пакет без требований к операционной системе, поэтому он работает везде, где работает Python — на Linux-серверах, на macOS и на Windows-машинах разработчиков.
Как Uvicorn соотносится с Daphne и Hypercorn?Это скорее взаимозаменяемые «родственники», а не конкуренты: ASGI позволяет любому серверу запускать любое приложение. Daphne была первым ASGI-сервером (её создали для Django Channels), Hypercorn добавляет trio как альтернативу asyncio, Mangum адаптирует ASGI-приложения для AWS Lambda, а Granian — сервер, написанный на Rust.
Зачем вообще придумали ASGI?В Python долго не было минимального низкоуровневого интерфейса между асинхронными серверами и фреймворками. ASGI закрыл этот пробел, чтобы общий набор инструментов работал со всеми асинхронными фреймворками, — Uvicorn как раз один из серверов, построенных на нём.
Uvicorn уже проверен в бою или это пока экспериментальный проект?Проверен в бою: проект развивается на GitHub с 2017 года и собрал более 11 000 звёзд.
Creator
Kludex
Size
5.6 MB
Stars
11K
Age
9y
Commits · 90 Days