starlette/README.md

176 lines
5.0 KiB
Markdown
Raw Normal View History

2018-07-02 10:52:33 +00:00
<p align="center">
2019-05-21 08:50:46 +00:00
<a href="https://www.starlette.io/"><img width="420px" src="https://raw.githubusercontent.com/encode/starlette/master/docs/img/starlette.png" alt='starlette'></a>
2018-07-02 10:52:33 +00:00
</p>
2018-06-25 13:19:28 +00:00
<p align="center">
<em>✨ The little ASGI framework that shines. ✨</em>
2018-06-25 13:19:28 +00:00
</p>
<p align="center">
2020-04-23 15:07:13 +00:00
<a href="https://github.com/encode/starlette/actions">
<img src="https://github.com/encode/starlette/workflows/Test%20Suite/badge.svg" alt="Build Status">
2018-06-25 13:19:28 +00:00
</a>
<a href="https://pypi.org/project/starlette/">
<img src="https://badge.fury.io/py/starlette.svg" alt="Package version">
</a>
</p>
2018-06-25 13:15:32 +00:00
2018-06-25 13:35:26 +00:00
---
2018-08-29 10:31:32 +00:00
**Documentation**: [https://www.starlette.io/](https://www.starlette.io/)
2019-06-19 11:54:26 +00:00
2018-08-29 10:33:59 +00:00
---
2018-12-11 13:07:16 +00:00
# Starlette
2018-10-16 15:10:24 +00:00
Starlette is a lightweight [ASGI](https://asgi.readthedocs.io/en/latest/) framework/toolkit,
anyio integration (#1157) * First whack at anyio integration * Fix formatting * Remove debug messages * mypy fixes * Update README.md Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com> * Fix install_requires typo * move_on_after blocks if deadline is too small * Linter fixes * Improve WSGI structured concurrency * Tests use anyio * Checkin progress on testclient * Prep for anyio 3 * Remove debug backend option * Use anyio 3.0.0rc1 * Remove old style executor from GraphQLApp * Fix extra import * Don't cancel task scope early * Wait for wsgi sender to finish before exiting * Use memory object streams in websocket tests * Test on asyncio, asyncio+uvloop, and trio * Formatting fixes * run_until_first_complete doesn't need a return * Fix middleware app call * Simplify middleware exceptions * Use anyio for websocket test * Set STARLETTE_TESTCLIENT_ASYNC_BACKEND in tests * Pass async backend to portal * Formatting fixes * Bump anyio * Cleanup portals and add TestClient.async_backend * Use anyio.run_async_from_thread to send from worker thread * Use websocket_connect as context manager * Document changes in TestClient * Formatting fix * Fix websocket raises coverage * Update to anyio 3.0.0rc3 and replace aiofiles * Apply suggestions from code review Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi> * Bump to require anyio 3.0.0 final * Remove mention of aiofiles in README.md * Pin jinja2 to releases before 3 due to DeprecationWarnings * Add task_group as application attribute * Remove run_until_first_complete * Undo jinja pin * Refactor anyio.sleep into an event * Use one less task in test_websocket_concurrency_pattern * Apply review suggestions * Rename argument * fix start_task_soon type * fix BaseHTTPMiddleware when used without Starlette * Testclient receive() is a non-trapping function if the response is already complete This allows for a zero deadline when waiting for a disconnect message * Use variable annotation for async_backend * Update docs regarding dependency on anyio * Use CancelScope instead of move_on_after in request.is_disconnected * Cancel task group after returning middleware response Add test for https://github.com/encode/starlette/issues/1022 * Add link to anyio backend options in testclient docs * Add types-dataclasses * Re-implement starlette.concurrency.run_until_first_complete and add a test * Fix type on handler callable * Apply review comments to clarify run_until_first_complete scope Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com> Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi> Co-authored-by: Thomas Grainger <tagrain@gmail.com>
2021-06-18 14:48:43 +00:00
which is ideal for building high performance async services.
2018-06-25 13:35:26 +00:00
2018-10-16 15:10:24 +00:00
It is production-ready, and gives you the following:
* Seriously impressive performance.
* WebSocket support.
* GraphQL support.
2018-10-16 15:10:24 +00:00
* In-process background tasks.
* Startup and shutdown events.
* Test client built on `requests`.
* CORS, GZip, Static Files, Streaming responses.
2018-10-29 16:49:13 +00:00
* Session and Cookie support.
2018-10-16 15:10:24 +00:00
* 100% test coverage.
* 100% type annotated codebase.
anyio integration (#1157) * First whack at anyio integration * Fix formatting * Remove debug messages * mypy fixes * Update README.md Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com> * Fix install_requires typo * move_on_after blocks if deadline is too small * Linter fixes * Improve WSGI structured concurrency * Tests use anyio * Checkin progress on testclient * Prep for anyio 3 * Remove debug backend option * Use anyio 3.0.0rc1 * Remove old style executor from GraphQLApp * Fix extra import * Don't cancel task scope early * Wait for wsgi sender to finish before exiting * Use memory object streams in websocket tests * Test on asyncio, asyncio+uvloop, and trio * Formatting fixes * run_until_first_complete doesn't need a return * Fix middleware app call * Simplify middleware exceptions * Use anyio for websocket test * Set STARLETTE_TESTCLIENT_ASYNC_BACKEND in tests * Pass async backend to portal * Formatting fixes * Bump anyio * Cleanup portals and add TestClient.async_backend * Use anyio.run_async_from_thread to send from worker thread * Use websocket_connect as context manager * Document changes in TestClient * Formatting fix * Fix websocket raises coverage * Update to anyio 3.0.0rc3 and replace aiofiles * Apply suggestions from code review Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi> * Bump to require anyio 3.0.0 final * Remove mention of aiofiles in README.md * Pin jinja2 to releases before 3 due to DeprecationWarnings * Add task_group as application attribute * Remove run_until_first_complete * Undo jinja pin * Refactor anyio.sleep into an event * Use one less task in test_websocket_concurrency_pattern * Apply review suggestions * Rename argument * fix start_task_soon type * fix BaseHTTPMiddleware when used without Starlette * Testclient receive() is a non-trapping function if the response is already complete This allows for a zero deadline when waiting for a disconnect message * Use variable annotation for async_backend * Update docs regarding dependency on anyio * Use CancelScope instead of move_on_after in request.is_disconnected * Cancel task group after returning middleware response Add test for https://github.com/encode/starlette/issues/1022 * Add link to anyio backend options in testclient docs * Add types-dataclasses * Re-implement starlette.concurrency.run_until_first_complete and add a test * Fix type on handler callable * Apply review comments to clarify run_until_first_complete scope Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com> Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi> Co-authored-by: Thomas Grainger <tagrain@gmail.com>
2021-06-18 14:48:43 +00:00
* Few hard dependencies.
* Compatible with `asyncio` and `trio` backends.
2018-06-25 13:35:26 +00:00
2018-08-29 10:31:32 +00:00
## Requirements
2018-06-25 13:58:51 +00:00
Python 3.6+
2018-08-29 10:31:32 +00:00
## Installation
2018-06-25 13:35:26 +00:00
```shell
2018-08-29 10:31:32 +00:00
$ pip3 install starlette
2018-06-25 13:35:26 +00:00
```
2018-06-25 13:24:50 +00:00
You'll also want to install an ASGI server, such as [uvicorn](http://www.uvicorn.org/), [daphne](https://github.com/django/daphne/), or [hypercorn](https://pgjones.gitlab.io/hypercorn/).
```shell
$ pip3 install uvicorn
```
2018-08-29 10:31:32 +00:00
## Example
2018-06-25 13:24:50 +00:00
**example.py**:
2018-06-25 13:15:32 +00:00
```python
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
2018-12-11 13:07:16 +00:00
2018-10-17 10:08:06 +00:00
async def homepage(request):
return JSONResponse({'hello': 'world'})
routes = [
Route("/", endpoint=homepage)
]
app = Starlette(debug=True, routes=routes)
```
Then run the application using Uvicorn:
```shell
$ uvicorn example:app
```
2018-12-11 13:07:16 +00:00
For a more complete example, see [encode/starlette-example](https://github.com/encode/starlette-example).
2018-11-08 13:12:37 +00:00
## Dependencies
anyio integration (#1157) * First whack at anyio integration * Fix formatting * Remove debug messages * mypy fixes * Update README.md Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com> * Fix install_requires typo * move_on_after blocks if deadline is too small * Linter fixes * Improve WSGI structured concurrency * Tests use anyio * Checkin progress on testclient * Prep for anyio 3 * Remove debug backend option * Use anyio 3.0.0rc1 * Remove old style executor from GraphQLApp * Fix extra import * Don't cancel task scope early * Wait for wsgi sender to finish before exiting * Use memory object streams in websocket tests * Test on asyncio, asyncio+uvloop, and trio * Formatting fixes * run_until_first_complete doesn't need a return * Fix middleware app call * Simplify middleware exceptions * Use anyio for websocket test * Set STARLETTE_TESTCLIENT_ASYNC_BACKEND in tests * Pass async backend to portal * Formatting fixes * Bump anyio * Cleanup portals and add TestClient.async_backend * Use anyio.run_async_from_thread to send from worker thread * Use websocket_connect as context manager * Document changes in TestClient * Formatting fix * Fix websocket raises coverage * Update to anyio 3.0.0rc3 and replace aiofiles * Apply suggestions from code review Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi> * Bump to require anyio 3.0.0 final * Remove mention of aiofiles in README.md * Pin jinja2 to releases before 3 due to DeprecationWarnings * Add task_group as application attribute * Remove run_until_first_complete * Undo jinja pin * Refactor anyio.sleep into an event * Use one less task in test_websocket_concurrency_pattern * Apply review suggestions * Rename argument * fix start_task_soon type * fix BaseHTTPMiddleware when used without Starlette * Testclient receive() is a non-trapping function if the response is already complete This allows for a zero deadline when waiting for a disconnect message * Use variable annotation for async_backend * Update docs regarding dependency on anyio * Use CancelScope instead of move_on_after in request.is_disconnected * Cancel task group after returning middleware response Add test for https://github.com/encode/starlette/issues/1022 * Add link to anyio backend options in testclient docs * Add types-dataclasses * Re-implement starlette.concurrency.run_until_first_complete and add a test * Fix type on handler callable * Apply review comments to clarify run_until_first_complete scope Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com> Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi> Co-authored-by: Thomas Grainger <tagrain@gmail.com>
2021-06-18 14:48:43 +00:00
Starlette only requires `anyio`, and the following are optional:
2018-10-31 09:42:07 +00:00
* [`requests`][requests] - Required if you want to use the `TestClient`.
2019-02-18 13:38:04 +00:00
* [`jinja2`][jinja2] - Required if you want to use `Jinja2Templates`.
2018-10-31 09:42:07 +00:00
* [`python-multipart`][python-multipart] - Required if you want to support form parsing, with `request.form()`.
* [`itsdangerous`][itsdangerous] - Required for `SessionMiddleware` support.
* [`pyyaml`][pyyaml] - Required for `SchemaGenerator` support.
* [`graphene`][graphene] - Required for `GraphQLApp` support.
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.
```python
from starlette.responses import PlainTextResponse
2018-06-25 13:15:32 +00:00
2019-06-24 09:46:46 +00:00
async def app(scope, receive, send):
assert scope['type'] == 'http'
response = PlainTextResponse('Hello, world!')
await response(scope, receive, send)
2018-06-25 13:15:32 +00:00
```
2019-06-24 09:46:46 +00:00
Run the `app` application in `example.py`:
2018-08-29 10:31:32 +00:00
```shell
2019-06-24 09:46:46 +00:00
$ uvicorn example:app
2018-08-29 10:31:32 +00:00
INFO: Started server process [11509]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
2019-03-11 14:35:30 +00:00
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
2018-11-05 12:08:34 +00:00
as [one of the fastest Python frameworks available](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=fortune&l=zijzen-1). *(\*)*
For high throughput loads you should:
2018-11-01 14:41:55 +00:00
* 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.
```shell
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.
2018-11-01 14:41:55 +00:00
Either programatically:
```python
uvicorn.run(..., http='h11', loop='asyncio')
```
Or using Gunicorn:
```shell
gunicorn -k uvicorn.workers.UvicornH11Worker ...
```
2018-08-29 10:31:32 +00:00
<p align="center">&mdash; ⭐️ &mdash;</p>
<p align="center"><i>Starlette is <a href="https://github.com/encode/starlette/blob/master/LICENSE.md">BSD licensed</a> code. Designed & built in Brighton, England.</i></p>
2018-10-31 09:39:10 +00:00
[requests]: http://docs.python-requests.org/en/master/
2018-11-08 16:36:39 +00:00
[jinja2]: http://jinja.pocoo.org/
2018-10-31 09:39:10 +00:00
[python-multipart]: https://andrew-d.github.io/python-multipart/
[graphene]: https://graphene-python.org/
[itsdangerous]: https://pythonhosted.org/itsdangerous/
2018-12-07 13:07:12 +00:00
[sqlalchemy]: https://www.sqlalchemy.org
[pyyaml]: https://pyyaml.org/wiki/PyYAMLDocumentation