pyboot-web
pyboot-web is the Starlette web plugin for
PyBoot. Its WebPlugin adds:
- Starlette application creation and lifespan management
- Decorator-based controllers and HTTP routes
- IoC-managed web services, components, and middleware
- HTTP exception advice
- CORS configuration
.envloading- Interval, fixed-delay, and timezone-aware cron jobs
- Background-job exception advice
The current package registers only WebPlugin in the
pyboot.plugins entry-point group. WebPlugin performs the web
registrations itself.
Requirements and installation
Python 3.11 or newer is required.
python -m pip install pyboot-framework pyboot-web apscheduler uvicorn
From this repository:
python -m pip install -e pyboot
python -m pip install -e plugins/pyboot_web
The package depends on Starlette, Pydantic, python-dotenv, and APScheduler.
Uvicorn is needed to serve the ASGI application.
Minimal application
Application classes must be below the package passed to bootstrap():
service/
├── main.py
└── app/
├── __init__.py
└── controllers.py
app/controllers.py:
from starlette.requests import Request
from starlette.responses import JSONResponse
from pyboot_web.rest_mapping import GetMapping, RestController
@RestController("/api")
class HealthController:
@GetMapping("/health")
async def health(self, request: Request) -> JSONResponse:
return JSONResponse({"status": "ok"})
main.py:
from pyboot import PyBoot
from pyboot_web.plugins.WebPlugin import WebPlugin
boot = PyBoot(debug=False)
boot.bootstrap(package="app")
app = boot.get_plugin(WebPlugin).app
Run it:
python -m uvicorn main:app --host 127.0.0.1 --port 8000
curl http://127.0.0.1:8000/api/health
WebPlugin creates the Starlette app. PyBoot does not accept an application
instance, and bootstrap() returns None.
Controllers and routes
Route decorators are intended for methods inside RestController classes:
from starlette.requests import Request
from starlette.responses import JSONResponse
from pyboot_web.rest_mapping import (
DeleteMapping,
GetMapping,
PatchMapping,
PostMapping,
PutMapping,
RestController,
)
@RestController("/api/users")
class UserController:
@GetMapping("")
async def list_users(self, request: Request) -> JSONResponse:
return JSONResponse({"items": []})
@GetMapping("/{user_id}")
async def get_user(self, request: Request) -> JSONResponse:
return JSONResponse({"id": request.path_params["user_id"]})
@PostMapping("")
async def create_user(self, request: Request) -> JSONResponse:
return JSONResponse(await request.json(), status_code=201)
@PutMapping("/{user_id}")
async def replace_user(self, request: Request) -> JSONResponse:
return JSONResponse({"id": request.path_params["user_id"]})
@PatchMapping("/{user_id}")
async def update_user(self, request: Request) -> JSONResponse:
return JSONResponse({"id": request.path_params["user_id"]})
@DeleteMapping("/{user_id}")
async def delete_user(self, request: Request) -> JSONResponse:
return JSONResponse({}, status_code=204)
RequestMapping stores HTTP methods as a list, so custom usage can map one
method decorator to the generated Starlette route. Path parameters, query
values, and headers come from Starlette's Request.
WebSocket controllers
Use WebSocketController with a WebSocketBase subclass to register a
Starlette WebSocket endpoint:
from starlette.websockets import WebSocket
from pyboot_web.websocket import WebSocketBase, WebSocketController
@WebSocketController("/ws", default_encoding="text")
class ChatSocket(WebSocketBase):
async def on_connect(self, websocket: WebSocket) -> None:
await websocket.accept()
async def on_receive(self, websocket: WebSocket, data: str) -> None:
await websocket.send_text(data)
The optional default_encoding can be "text", "bytes", or "json".
WebSocket controllers are created by Starlette rather than the IoC container.
Services and web components
Use WebService() for web-layer services:
from pyboot_web.service import WebService
@WebService()
class UserService:
def find_user(self, user_id: str) -> dict[str, str]:
return {"id": user_id, "name": "Ada"}
Use WebComponent() for other web-plugin-managed classes:
from pyboot_web.component import WebComponent
@WebComponent()
class RequestState:
def __init__(self) -> None:
self.value = "ready"
PyBoot's core Component() remains appropriate for general application
dependencies:
from pyboot.core.builtins.component import Component
@Component()
class AuditService:
def record(self, message: str) -> None:
print(message)
All three kinds can be injected through annotated constructors:
@RestController("/users")
class UserController:
def __init__(self, users: UserService) -> None:
self.users = users
Middleware
from starlette.requests import Request
from starlette.responses import Response
from pyboot_web.middlewares import (
CallNext,
MiddlewareBase,
MiddlewareComponent,
)
@MiddlewareComponent()
class RequestIdMiddleware(MiddlewareBase):
async def __call__(
self,
request: Request,
call_next: CallNext,
) -> Response:
response = await call_next(request)
response.headers["x-request-id"] = request.headers.get(
"x-request-id", "generated-request-id"
)
return response
Apply middleware to a controller or route with UseMiddleware:
from pyboot_web.middlewares import UseMiddleware
@RestController("/api")
@UseMiddleware([RequestIdMiddleware])
class HealthController:
@GetMapping("/health")
async def health(self, request: Request) -> JSONResponse:
return JSONResponse({"status": "ok"})
Pass middleware classes, not instances. Controller middleware wraps route middleware, which wraps the endpoint.
HTTP exception advice
from starlette.requests import Request
from starlette.responses import JSONResponse
from pyboot_web.exception_handler import ExceptionHandler, RestControllerAdvice
class UserNotFoundError(Exception):
pass
@RestControllerAdvice()
class ApiExceptionAdvice:
@ExceptionHandler(UserNotFoundError)
def user_not_found(
self,
request: Request,
exception: UserNotFoundError,
) -> JSONResponse:
return JSONResponse({"error": str(exception)}, status_code=404)
Handlers receive (request, exception) after self. Exact exception types
are checked first, followed by base classes. Unhandled exceptions are
re-raised.
Environment values
WebPlugin loads a .env file from the current working directory before
class discovery:
SERVICE_NAME=user-api
PORT=8000
DEBUG=false
Read values with Value:
from pyboot_web.value import Value
SERVICE_NAME = Value("SERVICE_NAME", "user-api")
PORT = int(Value("PORT", "8000"))
DEBUG = Value("DEBUG", "false").lower() == "true"
OPTIONAL = Value("OPTIONAL_SETTING", None, throw=False)
Value(key, default, throw=True) returns an environment value or default.
When both are None, the default behavior raises MissingValueException.
throw=False returns None instead. Convert values explicitly.
CORS
Provide a CorsConfiguration bean:
from pyboot.core.builtins.configuration import Bean, Configuration
from pyboot_web.cors import CorsConfiguration
@Configuration()
class WebConfiguration:
@Bean()
def cors(self) -> CorsConfiguration:
return CorsConfiguration(
allowed_origins=["http://localhost:3000"],
allowed_methods=["GET", "POST"],
allowed_headers=["content-type"],
allow_credentials=True,
max_age=600,
)
WebPlugin detects this bean and adds Starlette's CORSMiddleware.
Background jobs
from pyboot_web.bg_service import BackgroundService, IntervalSchedule
@BackgroundService()
class CleanupJobs:
@IntervalSchedule(interval_ms=60_000, initial_delay_ms=5_000)
async def cleanup(self) -> None:
print("cleanup")
For a fixed delay:
from pyboot_web.bg_service import BackgroundService, FixedDelaySchedule
@BackgroundService()
class PollingJobs:
@FixedDelaySchedule(fixed_delay_ms=30_000, initial_delay_ms=1_000)
async def poll(self) -> None:
print("poll")
For a timezone-aware cron job:
from datetime import timezone, timedelta
from pyboot_web.bg_service import BackgroundService, CronJob
india = timezone(timedelta(hours=5, minutes=30))
@BackgroundService()
class ReportJobs:
@CronJob("0 9 * * *", time_zone=india)
async def daily_report(self) -> None:
print("daily report")
Jobs are scheduled by APScheduler and start with the Starlette lifespan. Interval/fixed-delay values must be positive. Exceptions are routed through background exception advice when configured.
Background exception advice
from pyboot_web.bg_service_exception_handler import (
BackgroundExceptionHandler,
BackgroundServiceAdvice,
)
class ReportError(Exception):
pass
@BackgroundServiceAdvice()
class BackgroundAdvice:
@BackgroundExceptionHandler(ReportError)
def report_error(self, exception: ReportError) -> None:
print(f"background job failed: {exception}")
The handler receives the raised exception. Matching checks the exact type and then base classes. If no handler matches, the exception is re-raised.
Testing
from starlette.testclient import TestClient
from pyboot import PyBoot
from pyboot_web.plugins.WebPlugin import WebPlugin
def test_health() -> None:
boot = PyBoot()
boot.bootstrap("app")
client = TestClient(boot.get_plugin(WebPlugin).app)
response = client.get("/api/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
Related documentation
License
MIT. See LICENSE.
Metadata
Release files for pyboot-web 0.1.18
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pyboot_web-0.1.18.tar.gz | 17.5 kB | Without provenance | Details for pyboot_web-0.1.18.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyboot_web-0.1.18-py3-none-any.whl | Python 3 | none | any | Details for pyboot_web-0.1.18-py3-none-any.whl |
Total release size: 36.7 kB
Release files / pyboot_web-0.1.18.tar.gz
| Download URL | pyboot_web-0.1.18.tar.gz |
|---|---|
| Size | 17.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
81dae7f0ad45fef547b17901215a89070b2df0ce158b0abcf610412f056f26c1
|
|
BLAKE2b-256 checksum How to use checksums |
5bb887018ac315443a230ed6ca8b09bdc3ed40fc24e9a9731deacd86e79ec3f1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Release files / pyboot_web-0.1.18-py3-none-any.whl
| Download URL | pyboot_web-0.1.18-py3-none-any.whl |
|---|---|
| Size | 19.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
281a23f40308adf31a256b4c10ba9dd60d071a23de2adcc82922903e697d646e
|
|
BLAKE2b-256 checksum How to use checksums |
d6c7c69acc972040be6f687d09d4153d7930d20331eb91276705e93a0ba37a01
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Security for pyboot-web 0.1.18
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.