Fast web framework and HTTP client for Python asyncio
Project description
BlackSheep
BlackSheep is an asynchronous web framework to build event based, non-blocking Python web applications. It is inspired by Flask, ASP.NET Core, and the work by Yury Selivanov.
pip install blacksheep
from datetime import datetime
from blacksheep.server import Application
from blacksheep.server.responses import text
app = Application()
@app.route('/')
async def home(request):
return text(f'Hello, World! {datetime.utcnow().isoformat()}')
Getting started
Use these project templates to get started:
Requirements
BlackSheep belongs to the category of ASGI web frameworks, so it requires an ASGI HTTP server to run, such as uvicorn, daphne, 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:
# NB: 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 blacksheep.server.bindings import (FromJson,
FromHeader,
FromQuery,
FromRoute,
FromServices)
@app.router.put(b'/:d')
async def example(a: FromQuery(List[str]),
b: FromServices(Dog),
c: FromJson(Cat),
d: FromRoute(),
e: FromHeader(name='X-Example')):
...
@app.router.get(b'/:culture_code/:area')
async def home(request, culture_code, area):
return text(f'Request for: {culture_code} {area}')
It also supports dependency injection, provided by rodi, a library from the same author, supporting singleton
, scoped
, and transient
life style for activated services.
Strategies to handle authentication and authorization
BlackSheep implements strategies to handle authentication and authorization, using GuardPost, a library from the same author.
app.use_authentication()\
.add(ExampleAuthenticationHandler())
app.use_authorization()\
.add(AdminsPolicy())
@auth('admin')
@app.router.get(b'/')
async def only_for_admins():
...
@auth()
@app.router.get(b'/')
async def only_for_authenticated_users():
...
Objectives
- Intelligible and easy to learn API, similar to those of many Python web frameworks
- Rich code API, based on Dependency Injection and inspired by ASP.NET Core
- Keep the core package minimal and focused, as much as possible, on features defined in HTTP and HTML standards
- Targeting stateless applications to be deployed in the cloud
- High performance, see results from TechEmpower benchmarks (links in Wiki page)
Web framework features
- ASGI compatibility
- Routing
- Request handlers defined as functions, or class methods
- Middlewares
- Built-in support for dependency injection
- Support for automatic binding of route and query parameters to request handlers methods calls
- Strategy to handle exceptions
- Strategy to handle authentication and authorization
- Handlers normalization
- Chunked encoding through generators (yield syntax)
- Serving static files
- Integration with Jinja2
Client features
- HTTP connection pooling
- User friendly handling of SSL contexts (safe by default)
- Support for client side middlewares, enabling clean source code and separation of concerns (logging of different kinds, handling of cookies, etc.)
- Automatic handling of redirects (can be disabled, validates circular redirects and maximum number of redirects - redirects to URN are simply returned to code using the client)
- Automatic handling of cookies (can be disabled,
Set-Cookie
andCookie
headers)
Example:
import asyncio
from blacksheep.client import ClientSession
async def client_example(loop):
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)
loop = asyncio.get_event_loop()
loop.run_until_complete(client_example(loop))
Documentation
Please refer to the project Wiki.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.