MCPcopy Index your code
hub / github.com/Neoteroi/BlackSheep

github.com/Neoteroi/BlackSheep @v2.6.3

Chat with this repo
repository ↗ · DeepWiki ↗ · release v2.6.3 ↗ · + Follow
4,252 symbols 20,092 edges 189 files 785 documented · 18% 1 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Build pypi versions 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, timezone

from blacksheep import Application, get


app = Application()

@get("/")
async def home():
    return f"Hello, World! {datetime.now(timezone.utc).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.

Dependencies

Before version 2.3.1, BlackSheep only supported running with CPython and always depended on httptools. Starting with version 2.3.1, the framework supports running on PyPy and makes httptools an optional dependency.

Since version 2.5.0, the BlackSheep HTTP Client includes HTTP/2 support and requires h11 and h2 libraries.

For slightly better performance in URL parsing when running on CPython, it is recommended to install httptools (optional).

[!TIP]

The best performance can be achieved using PyPy runtime, and Socketify or Granian, (see #539 for more information).

Getting started with the documentation

The documentation offers getting started tutorials: * Getting started: basics * Getting started: the MVC project template

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, hypercorn or granian. 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, get, post


app = Application()


@dataclass
class CreateCatInput:
    name: str


@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`
    ...


@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}"


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


@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")
@get("/")
async def only_for_admins():
    ...


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

BlackSheep provides:

Meaning that it is easy to integrate with services such as: * Auth0 * Microsoft Entra ID * Azure Active Directory B2C * Okta

Since version 2.4.2, it also offers built-in support for Basic authentication, API Key authentication, JWT Bearer authentication using symmetric encryption, and automatic generation of OpenAPI Documentation for security schemes when using built-in classes for authentication. It supports defining custom authentication handlers and custom mappers for OpenAPI Documentation.

Refer to the documentation and to BlackSheep-Examples for more details and examples.

Web framework features

Client features

BlackSheep includes an HTTP Client with native HTTP/2 support (since version 2.5.0). The client automatically detects and uses HTTP/2 when the server supports it, with seamless fallback to HTTP/1.1.

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/")
        text = await response.text()
        print(text)


asyncio.run(client_example())

[!IMPORTANT]

Starting from version 2.3.1, BlackSheep supports PyPy (PyPy 3.11). The HTTP client requires h11 and h2 libraries. Version 2.5.0 added native HTTP/2 support via the h2 library. The httptools library is optional and only provides better URL parsing performance on CPython. These dependencies affect only the blacksheep.client namespace.

Supported platforms and runtimes

  • Python: all versions included in the build matrix.
  • CPython and PyPy.
  • Ubuntu.
  • Windows.
  • macOS.

Documentation

Please refer to the documentation website.

Branches

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

Core symbols most depended-on inside this repo

get_example_scope
called by 470
blacksheep/testing/helpers.py
append
called by 267
blacksheep/middlewares.py
start
called by 201
blacksheep/ranges.py
get
called by 189
blacksheep/headers.py
text
called by 173
blacksheep/messages.py
decode
called by 157
blacksheep/settings/encodings.py
text
called by 117
blacksheep/server/responses.py
get_single
called by 101
blacksheep/headers.py

Shape

Function 1,918
Method 1,462
Class 598
Route 274

Languages

Python100%

Modules by API surface

tests/test_application.py271 symbols
tests/test_openapi_v3.py234 symbols
blacksheep/server/bindings/__init__.py151 symbols
blacksheep/server/routing.py127 symbols
tests/test_controllers.py124 symbols
tests/test_bindings.py121 symbols
tests/test_router.py119 symbols
blacksheep/server/authentication/oidc.py115 symbols
itests/app_2.py96 symbols
blacksheep/server/openapi/v3.py91 symbols
blacksheep/server/application.py80 symbols
blacksheep/server/bindings/converters.py78 symbols

Used by 1 indexed graphs manifest dependencies, hub-wide

For agents

$ claude mcp add BlackSheep \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact