Starlette

闪亮的小 ASGI 框架。(The little ASGI framework that shines. )

  • Owner: encode/starlette
  • Platform: Linux, Mac, Windows
  • License:: BSD 3-Clause "New" or "Revised" License
  • Category::
  • Topic:
  • Like:
    2
      Compare:

Github stars Tracking Chart

Starlette

Starlette 是一个轻量级的 ASGI 框架/工具包,它是构建高性能 asyCIO 服务的理想选择。

它是生产就绪的,并为你提供了以下内容。

  • 令人印象深刻的性能
  • 支持 WebSocket。
  • 支持 GraphQL。
  • 进程中的后台任务。
  • 启动和关闭事件。
  • 建立在请求上的测试客户端。
  • CORS, GZip, Static Files, Streaming responses.
  • 支持会话和 Cookie。
  • 100% 的测试覆盖率。
  • 100% 的类型注释代码库。
  • 零硬性依赖。

要求

  • Python 3.6 以上

安装方法

$ pip3 install starlette

你还需要安装一个 ASGI 服务器,比如 uvicorn, daphne、或 hypercorn.

$ pip3 install uvicorn

例子

example.py

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
async def homepage(request):
    return JSONResponse({'hello': 'world'})
routes = [
    Route("/", endpoint=homepage)
]
app = Starlette(debug=True, routes=routes)

然后使用 Uvicorn 运行应用程序。

$ uvicorn example:app

更完整的例子,请看 encode/starlette-example

依赖性

Starlette 没有任何硬性的依赖关系,但以下是可选的。

  • requests -- 如果你想使用 TestClient,则需要。
  • aiofiles -- 如果你想使用 FileResponseStaticFiles,则需要。
  • jinja2 -- 如果你想使用 Jinja2Templates,则需要。
  • python-multipart -- 如果你想使用 request.form() 来支持表单解析,则需要。
  • itsdangerous -- 支持 SessionMiddleware 时需要。
  • pyyaml -- 支持 SchemaGenerator .时需要。
  • graphene -- 支持 GraphQLApp 时需要。
  • ujson -- 如果你想使用 UJSONResponse,则需要。

你可以用 pip3 install starlette[full] 来安装所有这些。

框架或工具包

Starlette 可以作为一个完整的框架使用,也可以作为 ASGI 工具箱使用。你可以独立使用它的任何组件。

from starlette.responses import PlainTextResponse
async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)

在 example.py 中运行应用程序:

$ uvicorn example:app
INFO: Started server process [11509]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

使用 --reload 运行 uvicorn,以实现代码更改时的自动重载。

模块化

Starlette 的模块化设计促进了可重用组件的建立,这些组件可以在任何 ASGI 框架之间共享。这应该可以建立一个共享中间件和可挂载应用的生态系统。

清晰的 API 分离也意味着更容易理解每个组件。

性能方面

独立的 TechEmpower 基准显示,在 Uvicorn 下运行的 Starlette 应用程序是 目前最快的 Python 框架之一。(*)

对于高吞吐量的负载,你应该:

  • 确保安装 ujson 并使用 UJSONResponse。
  • 使用 uvicorn worker 类使用 gunicorn 运行。
  • 每个 CPU 核使用一个或两个 worker。(你可能需要进行实验。)
  • 禁用访问日志。

例如

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

一些 ASGI 服务器也有纯 Python 的实现,所以如果你的应用代码有 CPU 限制的部分,你也可以在 PyPy 下运行。

无论是程序上的。

uvicorn.run(..., http='h11', loop='asyncio')

或者使用 Gunicorn。

gunicorn -k uvicorn.workers.UvicornH11Worker ...

许可证

Starlette 是 BSD licensed 代码。在英国布莱顿设计和建造。


(The first version translated by vz on 2020.10.03)

Main metrics

Overview
Name With Ownerencode/starlette
Primary LanguagePython
Program languageShell (Language Count: 2)
PlatformLinux, Mac, Windows
License:BSD 3-Clause "New" or "Revised" License
所有者活动
Created At2018-06-25 13:16:21
Pushed At2025-04-16 12:57:27
Last Commit At2025-04-16 13:57:27
Release Count172
Last Release Name0.46.2 (Posted on )
First Release Name0.1.0 (Posted on 2018-06-25 14:15:37)
用户参与
Stargazers Count10.9k
Watchers Count102
Fork Count1k
Commits Count1.5k
Has Issues Enabled
Issues Count745
Issue Open Count17
Pull Requests Count1136
Pull Requests Open Count24
Pull Requests Close Count497
项目设置
Has Wiki Enabled
Is Archived
Is Fork
Is Locked
Is Mirror
Is Private

Documentation: https://www.starlette.io/

Community: https://discuss.encode.io/c/starlette


Starlette

Starlette is a lightweight ASGI framework/toolkit,
which is ideal for building high performance asyncio services.

It is production-ready, and gives you the following:

  • Seriously impressive performance.
  • WebSocket support.
  • GraphQL support.
  • In-process background tasks.
  • Startup and shutdown events.
  • Test client built on requests.
  • CORS, GZip, Static Files, Streaming responses.
  • Session and Cookie support.
  • 100% test coverage.
  • 100% type annotated codebase.
  • Zero hard dependencies.

Requirements

Python 3.6+

Installation

$ pip3 install starlette

You'll also want to install an ASGI server, such as uvicorn, daphne, or hypercorn.

$ pip3 install uvicorn

Example

example.py:

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route


async def homepage(request):
    return JSONResponse({'hello': 'world'})

routes = [
    Route("/", endpoint=homepage)
]

app = Starlette(debug=True, routes=routes)

Then run the application using Uvicorn:

$ uvicorn example:app

For a more complete example, see encode/starlette-example.

Dependencies

Starlette does not have any hard dependencies, but the following are optional:

  • requests - Required if you want to use the TestClient.
  • aiofiles - Required if you want to use FileResponse or StaticFiles.
  • jinja2 - Required if you want to use Jinja2Templates.
  • python-multipart - Required if you want to support form parsing, with request.form().
  • itsdangerous - Required for SessionMiddleware support.
  • pyyaml - Required for SchemaGenerator support.
  • graphene - Required for GraphQLApp support.
  • ujson - Required if you want to use UJSONResponse.

You can install all of these with pip3 install starlette[full].

Framework or Toolkit

Starlette is designed to be used either as a complete framework, or as
an ASGI toolkit. You can use any of its components independently.

from starlette.responses import PlainTextResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)

Run the app application in example.py:

$ uvicorn example:app
INFO: Started server process [11509]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Run uvicorn with --reload to enable auto-reloading on code changes.

Modularity

The modularity that Starlette is designed on promotes building re-usable
components that can be shared between any ASGI framework. This should enable
an ecosystem of shared middleware and mountable applications.

The clean API separation also means it's easier to understand each component
in isolation.

Performance

Independent TechEmpower benchmarks show Starlette applications running under Uvicorn
as one of the fastest Python frameworks available. (*)

For high throughput loads you should:

  • Make sure to install ujson and use UJSONResponse.
  • Run using gunicorn using the uvicorn worker class.
  • Use one or two workers per-CPU core. (You might need to experiment with this.)
  • Disable access logging.

Eg.

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

Several of the ASGI servers also have pure Python implementations available,
so you can also run under PyPy if your application code has parts that are
CPU constrained.

Either programatically:

uvicorn.run(..., http='h11', loop='asyncio')

Or using Gunicorn:

gunicorn -k uvicorn.workers.UvicornH11Worker ...