Package: blacksheep
BlackSheepBlackSheep is an asynchronous web framework to build event based web
applications with Python. It is inspired byFlask,ASP.NET
Core, and the work byYury
Selivanov.pipinstallblacksheepfromdatetimeimportdatetimefromblacksheepimportApplication,getapp=Application()@get("/")asyncdefhome():returnf"Hello, World!{datetime.utcnow().isoformat()}"Getting started using the CLI ✨BlackSheep offers a CLI to bootstrap new projects rapidly.
To try it, first install theblacksheep-clipackage:pipinstallblacksheep-cliThen use theblacksheep createcommand to bootstrap a project
using one of the supported templates.The CLI includes a help, and supports custom templates, using the
same sources supported byCookiecutter.Getting started with the documentationThe documentation offers getting started tutorials:Getting started:
basicsGetting started: the MVC project
templateThese project templates can be used to start new applications faster:MVC project
templateEmpty project
templateRequirementsPython: any version listed in the project's
classifiers. The current list is:BlackSheep belongs to the category ofASGIweb frameworks, so it requires
an ASGI HTTP server to run, such asuvicorn, orhypercorn. For example, to use it with
uvicorn:$pipinstalluvicornTo 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`$uvicornserver:appTo run for production, refer to the documentation of the chosen ASGI server
(i.e. foruvicorn).Automatic bindings and dependency injectionBlackSheep supports automatic binding of values for request handlers, by type
annotation or by conventions. Seemore
here.fromdataclassesimportdataclassfromblacksheepimportApplication,FromJSON,FromQuery,get,postapp=Application()@dataclassclassCreateCatInput:name:str@post("/api/cats")asyncdefexample(data:FromJSON[CreateCatInput]):# in this example, data is bound automatically reading the JSON# payload and creating an instance of `CreateCatInput`...@get("/:culture_code/:area")asyncdefhome(culture_code,area):# in this example, both parameters are obtained from routes with# matching namesreturnf"Request for:{culture_code}{area}"@get("/api/products")defget_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")defget_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 supportsdependency
injection, a
feature that provides a consistent and clean way to use dependencies in request
handlers.Generation of OpenAPI DocumentationGeneration of OpenAPI Documentation.Strategies to handle authentication and authorizationBlackSheep implements strategies to handle authentication and authorization.
These features are documented here:AuthenticationAuthorizationapp.use_authentication()\.add(ExampleAuthenticationHandler())app.use_authorization()\.add(AdminsPolicy())@auth("admin")@get("/")asyncdefonly_for_admins():...@auth()@get("/")asyncdefonly_for_authenticated_users():...Since version1.2.1, BlackSheep implements:Built-in support for OpenID Connect authenticationBuilt-in support for JWT Bearer authenticationMeaning that it is easy to integrate with services such as:Auth0Azure Active DirectoryAzure Active Directory B2COktaRefer to the documentation and toBlackSheep-Examplesfor more details and examples.Web framework featuresASGI compatibilityRoutingRequest handlers can bedefined as
functions, orclass
methodsMiddlewaresWebSocketServer-Sent Events (SSE)Built-in support for dependency
injectionSupport for automatic binding of route and query parameters to request
handlers methods
callsStrategy to handle
exceptionsStrategy to handle authentication and
authorizationBuilt-in support for OpenID Connect authentication using OIDC
discoveryBuilt-in support for JWT Bearer authentication using OIDC discovery and
other sources of
JWKSHandlers
normalizationServing static
filesIntegration with
Jinja2Support for serving SPAs that use HTML5 History API for client side
routingSupport for automatic generation of OpenAPI
DocumentationStrategy to handle CORS settingsSessionsSupport for automatic binding ofdataclassesandpydanticmodels to handle the
request body payload expected by request handlersTestClientclass to simplify testing of applicationsAnti Forgery validationto protect against Cross-Site Request Forgery (XSRF/CSRF) attacksClient featuresBlackSheep includes an HTTP Client.Example:importasynciofromblacksheep.clientimportClientSessionasyncdefclient_example():asyncwithClientSession()asclient:response=awaitclient.get("https://docs.python.org/3/")text=awaitresponse.text()print(text)asyncio.run(client_example())Supported platforms and runtimesPython: all versions included in the build matrixUbuntuWindows 10macOSDocumentationPlease refer to thedocumentation website.CommunicationBlackSheep community in Gitter.BranchesThemainbranch contains the currently developed version, which is version 2. Thev1branch contains version 1 of the web framework, for bugs fixes
and maintenance.