Skip to content

Commit

Permalink
Merge branch 'master' into fix-staticfiles-follow-symlinks
Browse files Browse the repository at this point in the history
  • Loading branch information
aminalaee committed Jan 22, 2022
2 parents 5335c98 + 1974937 commit 3dee9ab
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 68 deletions.
18 changes: 13 additions & 5 deletions docs/authentication.md
Expand Up @@ -7,8 +7,7 @@ interfaces will be available in your endpoints.
```python
from starlette.applications import Starlette
from starlette.authentication import (
AuthenticationBackend, AuthenticationError, SimpleUser, UnauthenticatedUser,
AuthCredentials
AuthCredentials, AuthenticationBackend, AuthenticationError, SimpleUser
)
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
Expand All @@ -19,11 +18,11 @@ import binascii


class BasicAuthBackend(AuthenticationBackend):
async def authenticate(self, request):
if "Authorization" not in request.headers:
async def authenticate(self, conn):
if "Authorization" not in conn.headers:
return

auth = request.headers["Authorization"]
auth = conn.headers["Authorization"]
try:
scheme, credentials = auth.split()
if scheme.lower() != 'basic':
Expand Down Expand Up @@ -136,6 +135,10 @@ For class-based endpoints, you should wrap the decorator
around a method on the class.

```python
from starlette.authentication import requires
from starlette.endpoints import HTTPEndpoint


class Dashboard(HTTPEndpoint):
@requires("authenticated")
async def get(self, request):
Expand All @@ -148,6 +151,11 @@ You can customise the error response sent when a `AuthenticationError` is
raised by an auth backend:

```python
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse


def on_auth_error(request: Request, exc: Exception):
return JSONResponse({"error": str(exc)}, status_code=401)

Expand Down
8 changes: 8 additions & 0 deletions docs/middleware.md
Expand Up @@ -250,6 +250,10 @@ This middleware adds authentication to any ASGI application, requiring users to
using their GitHub account (via [OAuth](https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/)).
Access can be restricted to specific users or to members of specific GitHub organizations or teams.

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

Middleware for protecting against CSRF attacks. This middleware implements the Double Submit Cookie pattern, where a cookie is set, then it is compared to a csrftoken hidden form field or an `x-csrftoken` HTTP header.

#### [AuthlibMiddleware](https://github.com/aogier/starlette-authlib)

A drop-in replacement for Starlette session middleware, using [authlib's jwt](https://docs.authlib.org/en/latest/jose/jwt.html)
Expand All @@ -259,6 +263,10 @@ module.

A middleware class for logging exceptions to [Bugsnag](https://www.bugsnag.com/).

#### [CSRFMiddleware](https://github.com/frankie567/starlette-csrf)

Middleware for protecting against CSRF attacks. This middleware implements the Double Submit Cookie pattern, where a cookie is set, then it is compared to an `x-csrftoken` HTTP header.

#### [EarlyDataMiddleware](https://github.com/HarrySky/starlette-early-data)

Middleware and decorator for detecting and denying [TLSv1.3 early data](https://tools.ietf.org/html/rfc8470) requests.
Expand Down
14 changes: 14 additions & 0 deletions docs/templates.md
Expand Up @@ -64,6 +64,20 @@ def test_homepage():
assert "request" in response.context
```

## Customizing Jinja2 Environment

`Jinja2Templates` accepts all options supported by Jinja2 `Environment`.
This will allow more control over the `Enivornment` instance created by Starlette.

For the list of options available to `Environment` you can check Jinja2 documentation [here](https://jinja.palletsprojects.com/en/3.0.x/api/#jinja2.Environment)

```python
from starlette.templating import Jinja2Templates


templates = Jinja2Templates(directory='templates', autoescape=False, auto_reload=True)
```

## Asynchronous template rendering

Jinja2 supports async template rendering, however as a general rule
Expand Down
116 changes: 58 additions & 58 deletions docs/third-party-packages.md
Expand Up @@ -3,7 +3,6 @@ Starlette has a rapidly growing community of developers, building tools that int

Here are some of those third party packages:


## Backports

### Python 3.5 port
Expand All @@ -12,19 +11,25 @@ Here are some of those third party packages:

## Plugins

### Starlette APISpec
### Authlib

<a href="https://github.com/Woile/starlette-apispec" target="_blank">GitHub</a>
<a href="https://github.com/lepture/Authlib" target="_blank">GitHub</a> |
<a href="https://docs.authlib.org/en/latest/" target="_blank">Documentation</a>

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.
The ultimate Python library in building OAuth and OpenID Connect clients and servers. Check out how to integrate with [Starlette](https://docs.authlib.org/en/latest/client/starlette.html).

### SpecTree
### ChannelBox

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

Generate OpenAPI spec document and validate request & response with Python annotations. Less boilerplate code(no need for YAML).
Another solution for websocket broadcast. Send messages to channel groups from any part of your code.
Checkout <a href="https://channel-box.andrey-sobolev.ru/" target="_blank">MySimpleChat</a>, a simple chat application built using `channel-box` and `starlette`.

### Imia

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

An authentication framework for Starlette with pluggable authenticators and login/logout flow.

### Mangum

Expand All @@ -39,42 +44,39 @@ Serverless ASGI adapter for AWS Lambda & API Gateway.
Manage and send messages to groups of channels using websockets.
Checkout <a href="https://github.com/taoufik07/nejma-chat" target="_blank">nejma-chat</a>, a simple chat application built using `nejma` and `starlette`.

### ChannelBox

<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.
Checkout <a href="https://channel-box.andrey-sobolev.ru/" target="_blank">MySimpleChat</a>, a simple chat application built using `channel-box` and `starlette`.

### Scout APM

<a href="https://github.com/scoutapp/scout_apm_python" target="_blank">GitHub</a>

An APM (Application Performance Monitoring) solution that can
instrument your application to find performance bottlenecks.

### Starlette Prometheus
### SpecTree

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

A plugin for providing an endpoint that exposes [Prometheus](https://prometheus.io/) metrics based on its [official python client](https://github.com/prometheus/client_python).
Generate OpenAPI spec document and validate request & response with Python annotations. Less boilerplate code(no need for YAML).

### webargs-starlette
### Starlette APISpec

<a href="https://github.com/sloria/webargs-starlette" target="_blank">GitHub</a>
<a href="https://github.com/Woile/starlette-apispec" target="_blank">GitHub</a>

Declarative request parsing and validation for Starlette, built on top
of [webargs](https://github.com/marshmallow-code/webargs).
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.

Allows you to parse querystring, JSON, form, headers, and cookies using
type annotations.
### Starlette Context

### Authlib
<a href="https://github.com/tomwojcik/starlette-context" target="_blank">GitHub</a>

<a href="https://github.com/lepture/Authlib" target="_blank">GitHub</a> |
<a href="https://docs.authlib.org/en/latest/" target="_blank">Documentation</a>
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.

The ultimate Python library in building OAuth and OpenID Connect clients and servers. Check out how to integrate with [Starlette](https://docs.authlib.org/en/latest/client/starlette.html).
### 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.

### Starlette OAuth2 API

Expand All @@ -83,45 +85,36 @@ The ultimate Python library in building OAuth and OpenID Connect clients and ser
A starlette middleware to add authentication and authorization through JWTs.
It relies solely on an auth provider to issue access and/or id tokens to clients.

### Starlette Context
### Starlette Prometheus

<a href="https://github.com/tomwojcik/starlette-context" target="_blank">GitHub</a>
<a href="https://github.com/perdy/starlette-prometheus" target="_blank">GitHub</a>

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.
A plugin for providing an endpoint that exposes [Prometheus](https://prometheus.io/) metrics based on its [official python client](https://github.com/prometheus/client_python).

### Starlette WTF

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

A simple tool for integrating Starlette and WTForms. It is modeled on the excellent Flask-WTF library.

### Starsessions

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

An alternate session support implementation with customizable storage backends.

### webargs-starlette

### 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.


### Imia

<a href="https://github.com/alex-oleshkevich/imia" target="_blank">GitHub</a>
<a href="https://github.com/sloria/webargs-starlette" target="_blank">GitHub</a>

An authentication framework for Starlette with pluggable authenticators and login/logout flow.
Declarative request parsing and validation for Starlette, built on top
of [webargs](https://github.com/marshmallow-code/webargs).

Allows you to parse querystring, JSON, form, headers, and cookies using
type annotations.

## Frameworks

### Responder

<a href="https://github.com/taoufik07/responder" target="_blank">GitHub</a> |
<a href="https://python-responder.org/en/latest/" target="_blank">Documentation</a>

Async web service framework. Some Features: flask-style route expression,
yaml support, OpenAPI schema generation, background tasks, graphql.

### FastAPI

<a href="https://github.com/tiangolo/fastapi" target="_blank">GitHub</a> |
Expand All @@ -139,12 +132,6 @@ 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>

### Greppo

<a href="https://github.com/greppo-io/greppo" target="_blank">GitHub</a> |
Expand All @@ -154,3 +141,16 @@ A Python framework for building geospatial dashboards and web-applications.

Greppo is an open-source Python framework that makes it easy to build geospatial dashboards and web-applications. It provides a toolkit to quickly integrate data, algorithms, visualizations and UI for interactivity. It provides APIs to the update the variables in the backend, recompute the logic, and reflect the changes in the frontend (data mutation hook).

### Responder

<a href="https://github.com/taoufik07/responder" target="_blank">GitHub</a> |
<a href="https://python-responder.org/en/latest/" target="_blank">Documentation</a>

Async web service framework. Some Features: flask-style route expression,
yaml support, OpenAPI schema generation, background tasks, graphql.

### 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>
5 changes: 4 additions & 1 deletion starlette/applications.py
Expand Up @@ -44,7 +44,10 @@ def __init__(
routes: typing.Sequence[BaseRoute] = None,
middleware: typing.Sequence[Middleware] = None,
exception_handlers: typing.Mapping[
typing.Any, typing.Callable[[Request, Exception], Response]
typing.Any,
typing.Callable[
[Request, Exception], typing.Union[Response, typing.Awaitable[Response]]
],
] = None,
on_startup: typing.Sequence[typing.Callable] = None,
on_shutdown: typing.Sequence[typing.Callable] = None,
Expand Down
13 changes: 9 additions & 4 deletions starlette/templating.py
Expand Up @@ -55,20 +55,25 @@ class Jinja2Templates:
return templates.TemplateResponse("index.html", {"request": request})
"""

def __init__(self, directory: typing.Union[str, PathLike]) -> None:
def __init__(
self, directory: typing.Union[str, PathLike], **env_options: typing.Any
) -> None:
assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates"
self.env = self._create_env(directory)
self.env = self._create_env(directory, **env_options)

def _create_env(
self, directory: typing.Union[str, PathLike]
self, directory: typing.Union[str, PathLike], **env_options: typing.Any
) -> "jinja2.Environment":
@pass_context
def url_for(context: dict, name: str, **path_params: typing.Any) -> str:
request = context["request"]
return request.url_for(name, **path_params)

loader = jinja2.FileSystemLoader(directory)
env = jinja2.Environment(loader=loader, autoescape=True)
env_options.setdefault("loader", loader)
env_options.setdefault("autoescape", True)

env = jinja2.Environment(**env_options)
env.globals["url_for"] = url_for
return env

Expand Down

0 comments on commit 3dee9ab

Please sign in to comment.