• Stars
    star
    1,693
  • Rank 27,561 (Top 0.6 %)
  • Language
    Python
  • License
    MIT License
  • Created about 6 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Fast ASGI web framework for Python

Build pypi versions codecov license Join the chat at https://gitter.im/Neoteroi/BlackSheep documentation

BlackSheep

BlackSheep is an asynchronous web framework to build event based web applications with Python. It is inspired by Flask, ASP.NET Core, and the work by Yury Selivanov.

Black Sheep

pip install blacksheep

from datetime import datetime

from blacksheep import Application


app = Application()

@app.route("/")
async def home():
    return f"Hello, World! {datetime.utcnow().isoformat()}"

Getting started using the CLI ✨

BlackSheep offers a CLI to bootstrap new projects rapidly. To try it, first install the blacksheep-cli package:

pip install blacksheep-cli

Then use the blacksheep create command to bootstrap a project using one of the supported templates.

blacksheep create command

The CLI includes a help, and supports custom templates, using the same sources supported by Cookiecutter.

Getting started with the documentation

The documentation offers getting started tutorials:

These project templates can be used to start new applications faster:

Requirements

Python: any version listed in the project's classifiers. The current list is:

versions

BlackSheep belongs to the category of ASGI web frameworks, so it requires an ASGI HTTP server to run, such as uvicorn, or hypercorn. For example, to use it with uvicorn:

$ pip install uvicorn

To run an application like in the example above, use the methods provided by the ASGI HTTP Server:

# if the BlackSheep app is defined in a file `server.py`

$ uvicorn server:app

To run for production, refer to the documentation of the chosen ASGI server (i.e. for uvicorn).

Automatic bindings and dependency injection

BlackSheep supports automatic binding of values for request handlers, by type annotation or by conventions. See more here.

from dataclasses import dataclass

from blacksheep import Application, FromJSON, FromQuery


app = Application()


@dataclass
class CreateCatInput:
    name: str


@app.router.post("/api/cats")
async def example(data: FromJSON[CreateCatInput]):
    # in this example, data is bound automatically reading the JSON
    # payload and creating an instance of `CreateCatInput`
    ...


@app.router.get("/:culture_code/:area")
async def home(culture_code, area):
    # in this example, both parameters are obtained from routes with
    # matching names
    return f"Request for: {culture_code} {area}"


@app.router.get("/api/products")
def get_products(
    page: int = 1,
    size: int = 30,
    search: str = "",
):
    # this example illustrates support for implicit query parameters with
    # default values
    # since the source of page, size, and search is not specified and no
    # route parameter matches their name, they are obtained from query string
    ...


@app.router.get("/api/products2")
def get_products2(
    page: FromQuery[int] = FromQuery(1),
    size: FromQuery[int] = FromQuery(30),
    search: FromQuery[str] = FromQuery(""),
):
    # this example illustrates support for explicit query parameters with
    # default values
    # in this case, parameters are explicitly read from query string
    ...

It also supports dependency injection, a feature that provides a consistent and clean way to use dependencies in request handlers.

Generation of OpenAPI Documentation

Generation of OpenAPI Documentation.

Strategies to handle authentication and authorization

BlackSheep implements strategies to handle authentication and authorization. These features are documented here:

app.use_authentication()\
    .add(ExampleAuthenticationHandler())


app.use_authorization()\
    .add(AdminsPolicy())


@auth("admin")
@app.router.get("/")
async def only_for_admins():
    ...


@auth()
@app.router.get("/")
async def only_for_authenticated_users():
    ...

Since version 1.2.1, BlackSheep implements:

Meaning that it is easy to integrate with services such as:

Refer to the documentation for more details and examples.

Web framework features

Client features

BlackSheep includes an HTTP Client.

Example:

import asyncio

from blacksheep.client import ClientSession


async def client_example():
    async with ClientSession() as client:
        response = await client.get("https://docs.python.org/3/")

        assert response is not None
        text = await response.text()
        print(text)


asyncio.run(client_example())

Supported platforms and runtimes

  • Python: all versions included in the build matrix
  • Ubuntu
  • Windows 10
  • macOS

Documentation

Please refer to the documentation website.

Communication

BlackSheep community in Gitter.

Branches

The main branch contains the currently developed version, which is version 2 alpha. The v1 branch contains version 1 of the web framework, for bugs fixes and maintenance.