or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-blacksheep

Fast web framework for Python asyncio

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/blacksheep@1.2.x

To install, run

npx @tessl/cli install tessl/pypi-blacksheep@1.2.0

0

# BlackSheep - Python Web Framework

1

2

BlackSheep is a modern, high-performance Python web framework built with asyncio and Cython for optimal speed. It provides comprehensive server-side web application capabilities along with HTTP client functionality, designed for building scalable web services and APIs.

3

4

## Package Information

5

6

```python

7

# Package: blacksheep

8

# Requires Python: 3.8+

9

# Dependencies: guardpost, rodi, essentials

10

# Optional dependencies: uvicorn, hypercorn (ASGI servers)

11

```

12

13

## Core Imports

14

15

```python { .api }

16

from blacksheep import (

17

# Server Application

18

Application,

19

20

# HTTP Messages

21

Request, Response, Message,

22

23

# Content Types

24

Content, TextContent, HTMLContent, JSONContent,

25

FormContent, MultiPartFormData, StreamedContent, FormPart,

26

27

# Headers and Cookies

28

Headers, Header, Cookie, CookieSameSiteMode,

29

30

# URL and Routing

31

URL, Route, Router, RoutesRegistry,

32

33

# Request Bindings

34

FromJSON, FromQuery, FromRoute, FromForm,

35

FromHeader, FromCookie, FromServices, FromFiles,

36

FromBytes, FromText,

37

38

# Response Helpers

39

json, text, html, file, redirect,

40

ok, created, accepted, no_content,

41

bad_request, unauthorized, forbidden, not_found,

42

43

# Authentication & Authorization

44

auth, allow_anonymous,

45

46

# WebSocket Support

47

WebSocket, WebSocketState, WebSocketError,

48

49

# Exceptions

50

HTTPException, InvalidURL,

51

52

# Template Engine

53

use_templates,

54

)

55

```

56

57

## Client Imports

58

59

```python { .api }

60

from blacksheep.client import (

61

# HTTP Client

62

ClientSession,

63

64

# Client Exceptions

65

ConnectionTimeout, RequestTimeout,

66

CircularRedirectError, MaximumRedirectsExceededError,

67

)

68

```

69

70

## Basic Usage

71

72

### Simple Web Application

73

74

```python { .api }

75

from blacksheep import Application, get, json, text

76

77

app = Application()

78

79

@app.route("/")

80

async def home():

81

return text("Hello, BlackSheep!")

82

83

@app.route("/api/users/{user_id}")

84

async def get_user(user_id: int):

85

return json({"id": user_id, "name": f"User {user_id}"})

86

87

@app.route("/api/users", methods=["POST"])

88

async def create_user(data: FromJSON[dict]):

89

# data.value contains the parsed JSON

90

return json({"created": True, "data": data.value})

91

92

# Run with: uvicorn main:app

93

```

94

95

### HTTP Client Usage

96

97

```python { .api }

98

import asyncio

99

from blacksheep.client import ClientSession

100

from blacksheep import json as create_json_content

101

102

async def main():

103

async with ClientSession() as client:

104

# GET request

105

response = await client.get("https://api.example.com/users")

106

data = await response.json()

107

108

# POST with JSON

109

json_data = create_json_content({"name": "Alice"})

110

response = await client.post(

111

"https://api.example.com/users",

112

content=json_data

113

)

114

115

print(f"Status: {response.status}")

116

117

asyncio.run(main())

118

```

119

120

## Framework Capabilities

121

122

### πŸš€ [Core Server Functionality](./core-server.md)

123

- **Application**: Main server application class with lifecycle management

124

- **Routing**: Advanced URL routing with parameter extraction and type conversion

125

- **Middleware**: Request/response processing pipeline with built-in and custom middleware

126

- **Dependency Injection**: Service container with automatic resolution

127

- **Static Files**: Efficient static file serving with caching and security

128

129

Key APIs:

130

```python { .api }

131

app = Application(debug=True)

132

app.route("/users/{user_id:int}") # Route with typed parameters

133

app.use_cors() # CORS middleware

134

app.serve_files("./static") # Static file serving

135

```

136

137

### πŸ“¨ [Request/Response Handling](./request-response.md)

138

- **HTTP Messages**: Request and Response classes with rich functionality

139

- **Content Types**: Support for JSON, HTML, forms, multipart, streaming content

140

- **Headers**: Case-insensitive header handling with manipulation methods

141

- **URL Parsing**: Comprehensive URL manipulation and validation

142

- **Content Negotiation**: Automatic content type detection and parsing

143

144

Key APIs:

145

```python { .api }

146

# Request data binding

147

async def handler(user: FromJSON[User], id: FromRoute[int]):

148

pass

149

150

# Response creation

151

return json(data) # JSON response

152

return file("image.jpg") # File response

153

return redirect("/home") # Redirect response

154

```

155

156

### πŸ” [Authentication & Authorization](./auth.md)

157

- **JWT Authentication**: Bearer token validation with OIDC support

158

- **Cookie Authentication**: Secure cookie-based authentication

159

- **Authorization Policies**: Role-based and policy-based access control

160

- **Decorators**: Simple auth decorators for endpoints

161

- **Session Management**: Secure session handling with encryption

162

163

Key APIs:

164

```python { .api }

165

@auth("admin") # Require admin role

166

async def admin_only():

167

pass

168

169

@allow_anonymous

170

async def public_endpoint():

171

pass

172

173

# JWT configuration

174

app.use_authentication().add_jwt_bearer(audiences=["api"])

175

```

176

177

### 🌐 [HTTP Client](./client.md)

178

- **ClientSession**: Full-featured async HTTP client

179

- **Connection Pooling**: Automatic connection management

180

- **Redirects**: Configurable redirect handling

181

- **SSL Support**: Custom SSL context configuration

182

- **Timeouts**: Connection and request timeout controls

183

- **Middlewares**: Client-side middleware support

184

185

Key APIs:

186

```python { .api }

187

async with ClientSession() as client:

188

response = await client.get("https://api.com")

189

data = await response.json()

190

```

191

192

### πŸ”Œ [WebSocket Support](./websockets.md)

193

- **WebSocket Handler**: Full-duplex communication support

194

- **State Management**: Connection lifecycle tracking

195

- **JSON Messages**: Built-in JSON message serialization

196

- **Route Integration**: WebSocket routes with parameter extraction

197

- **Error Handling**: Comprehensive WebSocket exception handling

198

199

Key APIs:

200

```python { .api }

201

@app.ws("/chat/{room}")

202

async def chat_handler(websocket: WebSocket, room: str):

203

await websocket.accept()

204

await websocket.send_text(f"Joined room: {room}")

205

```

206

207

### πŸ§ͺ [Testing Utilities](./testing.md)

208

- **TestClient**: HTTP client simulation for testing

209

- **Mock Objects**: ASGI mocks for unit testing

210

- **Integration Testing**: Full application testing support

211

- **Async Testing**: Asyncio-compatible test utilities

212

- **Request Simulation**: Complete HTTP request simulation

213

214

Key APIs:

215

```python { .api }

216

from blacksheep.testing import TestClient

217

218

client = TestClient(app)

219

response = await client.get("/api/users")

220

assert response.status == 200

221

```

222

223

### ⚑ [Additional Features](./additional.md)

224

- **CORS**: Cross-Origin Resource Sharing with flexible policies

225

- **CSRF Protection**: Cross-Site Request Forgery mitigation

226

- **Sessions**: Encrypted session management

227

- **OpenAPI**: Automatic API documentation generation

228

- **Compression**: Response compression (gzip)

229

- **Security Headers**: HSTS and security header middleware

230

- **File Uploads**: Multipart form and file upload handling

231

- **Templating**: Template engine integration

232

- **Error Handling**: Comprehensive exception handling system

233

234

## Framework Architecture

235

236

BlackSheep follows these design principles:

237

238

1. **Async-First**: Built specifically for asyncio with no synchronous compatibility layer

239

2. **Type Safety**: Comprehensive type annotations and runtime type checking

240

3. **Performance**: Cython-optimized core components for maximum speed

241

4. **Modularity**: Clean separation of concerns with optional components

242

5. **Standards Compliance**: Full HTTP/1.1, WebSocket, and ASGI specification support

243

6. **Developer Experience**: Rich debugging, testing, and documentation tools

244

245

## Quick Reference

246

247

### Status Code Responses

248

```python { .api }

249

from blacksheep import ok, created, bad_request, not_found, unauthorized

250

251

return ok({"message": "Success"}) # 200

252

return created({"id": 123}) # 201

253

return bad_request({"error": "Invalid"}) # 400

254

return unauthorized() # 401

255

return not_found() # 404

256

```

257

258

### Request Data Binding

259

```python { .api }

260

async def endpoint(

261

id: FromRoute[int], # URL parameter

262

q: FromQuery[str], # Query parameter

263

data: FromJSON[MyModel], # JSON body

264

file: FromFiles, # Uploaded files

265

token: FromHeader[str], # Header value

266

session_id: FromCookie[str], # Cookie value

267

service: FromServices[MyService], # DI service

268

):

269

pass

270

```

271

272

### Content Types

273

```python { .api }

274

from blacksheep import TextContent, JSONContent, FormContent

275

276

return Response(200, content=TextContent("Hello"))

277

return Response(200, content=JSONContent({"key": "value"}))

278

return Response(200, content=FormContent({"field": "value"}))

279

```

280

281

For detailed information about each component, see the respective documentation sections linked above.