Skip to content

Commit

Permalink
Merge master
Browse files Browse the repository at this point in the history
  • Loading branch information
Kludex committed Sep 30, 2021
2 parents ceee483 + 6c556f6 commit ad29baa
Show file tree
Hide file tree
Showing 62 changed files with 1,336 additions and 712 deletions.
1 change: 1 addition & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
github: encode
2 changes: 1 addition & 1 deletion .github/workflows/test-suite.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:

strategy:
matrix:
python-version: ["3.6", "3.7", "3.8", "3.9"]
python-version: ["3.6", "3.7", "3.8", "3.9", "3.10.0-beta.3"]

steps:
- uses: "actions/checkout@v2"
Expand Down
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
# Starlette

Starlette is a lightweight [ASGI](https://asgi.readthedocs.io/en/latest/) framework/toolkit,
which is ideal for building high performance asyncio services.
which is ideal for building high performance async services.

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

Expand All @@ -35,7 +35,8 @@ It is production-ready, and gives you the following:
* Session and Cookie support.
* 100% test coverage.
* 100% type annotated codebase.
* Zero hard dependencies.
* Few hard dependencies.
* Compatible with `asyncio` and `trio` backends.

## Requirements

Expand Down Expand Up @@ -83,10 +84,9 @@ For a more complete example, see [encode/starlette-example](https://github.com/e

## Dependencies

Starlette does not have any hard dependencies, but the following are optional:
Starlette only requires `anyio`, and the following are optional:

* [`requests`][requests] - Required if you want to use the `TestClient`.
* [`aiofiles`][aiofiles] - Required if you want to use `FileResponse` or `StaticFiles`.
* [`jinja2`][jinja2] - Required if you want to use `Jinja2Templates`.
* [`python-multipart`][python-multipart] - Required if you want to support form parsing, with `request.form()`.
* [`itsdangerous`][itsdangerous] - Required for `SessionMiddleware` support.
Expand Down Expand Up @@ -165,7 +165,6 @@ gunicorn -k uvicorn.workers.UvicornH11Worker ...
<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>

[requests]: http://docs.python-requests.org/en/master/
[aiofiles]: https://github.com/Tinche/aiofiles
[jinja2]: http://jinja.pocoo.org/
[python-multipart]: https://andrew-d.github.io/python-multipart/
[graphene]: https://graphene-python.org/
Expand Down
4 changes: 2 additions & 2 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ organisations = sqlalchemy.Table(
```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.session import SessionMiddleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.routing import Route
from myproject import settings

Expand Down Expand Up @@ -192,7 +192,7 @@ and drop it once the tests complete. We'd also like to ensure
from starlette.config import environ
from starlette.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
from sqlalchemy_utils import create_database, database_exists, drop_database

# This line would raise an error if we use it after 'settings' has been imported.
environ['TESTING'] = 'TRUE'
Expand Down
4 changes: 2 additions & 2 deletions docs/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,10 @@ async def populate_note(request):
await database.execute(query)
raise RuntimeError()
except:
transaction.rollback()
await transaction.rollback()
raise
else:
transaction.commit()
await transaction.commit()
```

## Test isolation
Expand Down
25 changes: 25 additions & 0 deletions docs/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,31 @@ registered startup handlers have completed.
The shutdown handlers will run once all connections have been closed, and
any in-process background tasks have completed.

A single lifespan asynccontextmanager handler can be used instead of
separate startup and shutdown handlers:

```python
import contextlib
import anyio
from starlette.applications import Starlette


@contextlib.asynccontextmanager
async def lifespan(app):
async with some_async_resource():
yield


routes = [
...
]

app = Starlette(routes=routes, lifespan=lifespan)
```

Consider using [`anyio.create_task_group()`](https://anyio.readthedocs.io/en/stable/tasks.html)
for managing asynchronious tasks.

## Running event handlers in tests

You might want to explicitly call into your event handlers in any test setup
Expand Down
Binary file removed docs/img/graphiql.png
Binary file not shown.
6 changes: 2 additions & 4 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ It is production-ready, and gives you the following:
* Session and Cookie support.
* 100% test coverage.
* 100% type annotated codebase.
* Zero hard dependencies.
* Few hard dependencies.

## Requirements

Expand Down Expand Up @@ -79,10 +79,9 @@ For a more complete example, [see here](https://github.com/encode/starlette-exam

## Dependencies

Starlette does not have any hard dependencies, but the following are optional:
Starlette only requires `anyio`, and the following dependencies are optional:

* [`requests`][requests] - Required if you want to use the `TestClient`.
* [`aiofiles`][aiofiles] - Required if you want to use `FileResponse` or `StaticFiles`.
* [`jinja2`][jinja2] - Required if you want to use `Jinja2Templates`.
* [`python-multipart`][python-multipart] - Required if you want to support form parsing, with `request.form()`.
* [`itsdangerous`][itsdangerous] - Required for `SessionMiddleware` support.
Expand Down Expand Up @@ -161,7 +160,6 @@ gunicorn -k uvicorn.workers.UvicornH11Worker ...
<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>

[requests]: http://docs.python-requests.org/en/master/
[aiofiles]: https://github.com/Tinche/aiofiles
[jinja2]: http://jinja.pocoo.org/
[python-multipart]: https://andrew-d.github.io/python-multipart/
[graphene]: https://graphene-python.org/
Expand Down
4 changes: 3 additions & 1 deletion docs/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ To implement a middleware class using `BaseHTTPMiddleware`, you must override th
`async def dispatch(request, call_next)` method.

```python
from starlette.middleware.base import BaseHTTPMiddleware

class CustomHeaderMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
Expand Down Expand Up @@ -256,7 +258,7 @@ when proxy servers are being used, based on the `X-Forwarded-Proto` and `X-Forwa
A middleware class to emit timing information (cpu and wall time) for each request which
passes through it. Includes examples for how to emit these timings as statsd metrics.

#### [datasette-auth-github](https://github.com/simonw/datasette-auth-github)
#### [asgi-auth-github](https://github.com/simonw/asgi-auth-github)

This middleware adds authentication to any ASGI application, requiring users to sign in
using their GitHub account (via [OAuth](https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/)).
Expand Down
52 changes: 52 additions & 0 deletions docs/overrides/partials/nav.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!-- Determine class according to configuration -->
{% set class = "md-nav md-nav--primary" %}
{% if "navigation.tabs" in features %}
{% set class = class ~ " md-nav--lifted" %}
{% endif %}
{% if "toc.integrate" in features %}
{% set class = class ~ " md-nav--integrated" %}
{% endif %}

<!-- Main navigation -->
<nav
class="{{ class }}"
aria-label="{{ lang.t('nav.title') }}"
data-md-level="0"
>

<!-- Site title -->
<label class="md-nav__title" for="__drawer">
<a
href="{{ config.extra.homepage | d(nav.homepage.url, true) | url }}"
title="{{ config.site_name | e }}"
class="md-nav__button md-logo"
aria-label="{{ config.site_name }}"
data-md-component="logo"
>
{% include "partials/logo.html" %}
</a>
{{ config.site_name }}
</label>

<!-- Repository information -->
{% if config.repo_url %}
<div class="md-nav__source">
{% include "partials/source.html" %}
</div>
{% endif %}

<!-- Render item list -->
<ul class="md-nav__list" data-md-scrollfix>
{% for nav_item in nav %}
{% set path = "__nav_" ~ loop.index %}
{% set level = 1 %}
{% include "partials/nav-item.html" %}
{% endfor %}
</ul>

<ul class="md-nav__list" data-md-scrollfix style="padding-top: 15px; padding-left: 10px">
<div>
<a href="https://fastapi.tiangolo.com"><img src="/sponsors/fastapi.png" width=150px style=></img></a>
</div>
</ul>
</nav>
67 changes: 64 additions & 3 deletions docs/release-notes.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,72 @@
## 0.16.0

July 19, 2021

### Added
* Added [Encode](https://github.com/sponsors/encode) funding option
[#1219](https://github.com/encode/starlette/pull/1219)

### Fixed
* `starlette.websockets.WebSocket` instances are now hashable and compare by identity
[#1039](https://github.com/encode/starlette/pull/1039)
* A number of fixes related to running task groups in lifespan
[#1213](https://github.com/encode/starlette/pull/1213),
[#1227](https://github.com/encode/starlette/pull/1227)

### Deprecated/removed
* The method `starlette.templates.Jinja2Templates.get_env` was removed
[#1218](https://github.com/encode/starlette/pull/1218)
* The ClassVar `starlette.testclient.TestClient.async_backend` was removed,
the backend is now configured using constructor kwargs
[#1211](https://github.com/encode/starlette/pull/1211)
* Passing an Async Generator Function or a Generator Function to `starlette.router.Router(lifespan_context=)` is deprecated. You should wrap your lifespan in `@contextlib.asynccontextmanager`.
[#1227](https://github.com/encode/starlette/pull/1227)
[#1110](https://github.com/encode/starlette/pull/1110)

## 0.15.0

Unreleased
June 23, 2021

This release includes major changes to the low-level asynchronous parts of Starlette. As a result,
**Starlette now depends on [AnyIO](https://anyio.readthedocs.io/en/stable/)** and some minor API
changes have occurred. Another significant change with this release is the
**deprecation of built-in GraphQL support**.

### Deprecated
### Added
* Starlette now supports [Trio](https://trio.readthedocs.io/en/stable/) as an async runtime via
AnyIO - [#1157](https://github.com/encode/starlette/pull/1157).
* `TestClient.websocket_connect()` now must be used as a context manager.
* Initial support for Python 3.10 - [#1201](https://github.com/encode/starlette/pull/1201).
* The compression level used in `GZipMiddleware` is now adjustable -
[#1128](https://github.com/encode/starlette/pull/1128).

### Fixed
* Several fixes to `CORSMiddleware`. See [#1111](https://github.com/encode/starlette/pull/1111),
[#1112](https://github.com/encode/starlette/pull/1112),
[#1113](https://github.com/encode/starlette/pull/1113),
[#1199](https://github.com/encode/starlette/pull/1199).
* Improved exception messages in the case of duplicated path parameter names -
[#1177](https://github.com/encode/starlette/pull/1177).
* `RedirectResponse` now uses `quote` instead of `quote_plus` encoding for the `Location` header
to better match the behaviour in other frameworks such as Django -
[#1164](https://github.com/encode/starlette/pull/1164).
* Exception causes are now preserved in more cases -
[#1158](https://github.com/encode/starlette/pull/1158).
* Session cookies now use the ASGI root path in the case of mounted applications -
[#1147](https://github.com/encode/starlette/pull/1147).
* Fixed a cache invalidation bug when static files were deleted in certain circumstances -
[#1023](https://github.com/encode/starlette/pull/1023).
* Improved memory usage of `BaseHTTPMiddleware` when handling large responses -
[#1012](https://github.com/encode/starlette/issues/1012) fixed via #1157

### Deprecated/removed

* Built-in GraphQL support via the `GraphQLApp` class has been deprecated and will be removed in a
future release. Please see [#619](https://github.com/encode/starlette/issues/619).
future release. Please see [#619](https://github.com/encode/starlette/issues/619). GraphQL is not
supported on Python 3.10.
* The `executor` parameter to `GraphQLApp` was removed. Use `executor_class` instead.
* The `workers` parameter to `WSGIMiddleware` was removed. This hasn't had any effect since
Starlette v0.6.3.

## 0.14.2

Expand Down
7 changes: 3 additions & 4 deletions docs/responses.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,8 @@ async def app(scope, receive, send):
await response(scope, receive, send)
```

## Third party middleware
## Third party responses

### [SSEResponse(EventSourceResponse)](https://github.com/sysid/sse-starlette)
#### [EventSourceResponse](https://github.com/sysid/sse-starlette)

Server Sent Response implements the ServerSentEvent Protocol: https://www.w3.org/TR/2009/WD-eventsource-20090421.
It enables event streaming from the server to the client without the complexity of websockets.
A response class that implements [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html). It enables event streaming from the server to the client without the complexity of websockets.
2 changes: 1 addition & 1 deletion docs/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ routes = [
Route("/schema", endpoint=openapi_schema, include_in_schema=False)
]

app = Starlette()
app = Starlette(routes=routes)
```

We can now access an OpenAPI schema at the "/schema" endpoint.
Expand Down
Binary file added docs/sponsors/fastapi.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions docs/testclient.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,29 @@ application. Occasionally you might want to test the content of 500 error
responses, rather than allowing client to raise the server exception. In this
case you should use `client = TestClient(app, raise_server_exceptions=False)`.

### Selecting the Async backend

`TestClient` takes arguments `backend` (a string) and `backend_options` (a dictionary).
These options are passed to `anyio.start_blocking_portal()`. See the [anyio documentation](https://anyio.readthedocs.io/en/stable/basics.html#backend-options)
for more information about the accepted backend options.
By default, `asyncio` is used with default options.

To run `Trio`, pass `backend="trio"`. For example:

```python
def test_app()
with TestClient(app, backend="trio") as client:
...
```

To run `asyncio` with `uvloop`, pass `backend_options={"use_uvloop": True}`. For example:

```python
def test_app()
with TestClient(app, backend_options={"use_uvloop": True}) as client:
...
```

### Testing WebSocket sessions

You can also test websocket sessions with the test client.
Expand Down Expand Up @@ -72,6 +95,8 @@ always raised by the test client.

May raise `starlette.websockets.WebSocketDisconnect` if the application does not accept the websocket connection.

`websocket_connect()` must be used as a context manager (in a `with` block).

#### Sending data

* `.send_text(data)` - Send the given text to the application.
Expand Down
25 changes: 23 additions & 2 deletions docs/third-party-packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Simple APISpec integration for Starlette.
Document your REST API built with Starlette by declaring OpenAPI (Swagger)
schemas in YAML format in your endpoint's docstrings.

### SpecTree
### SpecTree

<a href="https://github.com/0b01001001/spectree" target="_blank">GitHub</a>

Expand All @@ -43,7 +43,7 @@ Checkout <a href="https://github.com/taoufik07/nejma-chat" target="_blank">nejma

<a href="https://github.com/Sobolev5/channel-box" target="_blank">GitHub</a>

Another solution for websocket broadcast. Send messages to channel groups from any part of your code.
Another solution for websocket broadcast. Send messages to channel groups from any part of your code.
Checkout <a href="https://svue-backend.andrey-sobolev.ru/chat/chat1/" target="_blank">channel-box-chat</a>, a simple chat application built using `channel-box` and `starlette`.

### Scout APM
Expand Down Expand Up @@ -90,6 +90,21 @@ It relies solely on an auth provider to issue access and/or id tokens to clients
Middleware for Starlette that allows you to store and access the context data of a request.
Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.


### Starsessions

<a href="https://github.com/alex-oleshkevich/starsessions" target="_blank">GitHub</a>

An alternate session support implementation with customizable storage backends.


### Starlette Cramjam

<a href="https://github.com/developmentseed/starlette-cramjam" target="_blank">GitHub</a>

A Starlette middleware that allows **brotli**, **gzip** and **deflate** compression algorithm with a minimal requirements.


## Frameworks

### Responder
Expand All @@ -116,3 +131,9 @@ Inspired by **APIStar**'s previous server system with type declarations for rout
Formerly Starlette API.

Flama aims to bring a layer on top of Starlette to provide an **easy to learn** and **fast to develop** approach for building **highly performant** GraphQL and REST APIs. In the same way of Starlette is, Flama is a perfect option for developing **asynchronous** and **production-ready** services.

### Starlette-apps

Roll your own framework with a simple app system, like [Django-GDAPS](https://gdaps.readthedocs.io/en/latest/) or [CakePHP](https://cakephp.org/).

<a href="https://github.com/yourlabs/starlette-apps" target="_blank">GitHub</a>
Loading

0 comments on commit ad29baa

Please sign in to comment.