Piccolo API Utilities
Piccolo API provides utilities for integrating the Piccolo ORM with ASGI applications. It includes essential ASGI middleware for common tasks like authentication (JWT, sessions, MFA) and rate limiting. The library is actively maintained, with regular releases (currently v1.9.0) addressing dependency updates, Python version support, and new features like Multi-Factor Authentication.
Common errors
-
ModuleNotFoundError: No module named 'cryptography'
cause You are attempting to use Multi-Factor Authentication (MFA) features without having the necessary optional dependencies installed.fixInstall `piccolo-api` with the `mfa` extra: `pip install "piccolo-api[mfa]"` (or `pynacl` if that's the missing module). -
pydantic_core._pydantic_core.ValidationError: Input should be a valid string
cause This (or similar Pydantic validation errors) can occur due to an incompatibility between `piccolo-api < 1.4.1` and `Pydantic >= 2.8.0`.fixUpgrade `piccolo-api` to `1.4.1` or newer: `pip install --upgrade piccolo-api`. Ensure your `pyproject.toml` or `requirements.txt` specifies a compatible version. -
RuntimeError: Your current Python version is 3.9.13 but Piccolo API requires >=3.10
cause You are running `piccolo-api` on an unsupported Python version. Python 3.8 and 3.9 were dropped in `piccolo-api` v1.6.0.fixUpgrade your Python environment to version 3.10 or newer.
Warnings
- breaking Python 3.8 and 3.9 are no longer supported since `piccolo-api` version 1.6.0. The library now requires Python >= 3.10.
- breaking Pydantic 2.8.0 introduced breaking changes that caused issues with `piccolo-api` versions prior to 1.4.1. If you use Pydantic 2.8.0 or newer with an older `piccolo-api`, you may encounter validation errors.
- gotcha Multi-Factor Authentication (MFA) features require additional optional dependencies (`cryptography` and `pynacl`). Using MFA without these installed will result in `ModuleNotFoundError`.
- gotcha When configuring Multi-Factor Authentication (MFA), it's highly recommended to provide sensitive encryption keys (e.g., `MFA_ENCRYPTION_KEY`) using environment variables for security reasons, rather than hardcoding them.
Install
-
pip install piccolo-api -
pip install "piccolo-api[mfa]"
Imports
- JWTAuth
from piccolo_api.middleware.auth.jwt import JWTAuth
from piccolo_api import JWTAuth
- SessionsAuthBackend
from piccolo_api.middleware.auth.sessions import SessionsAuthBackend
from piccolo_api import SessionsAuthBackend
- RateLimitMiddleware
from piccolo_api.rate_limit import RateLimitMiddleware
from piccolo_api import RateLimitMiddleware
Quickstart
import os
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from piccolo_api import JWTAuth
# For demonstration, typically loaded from environment variables
SECRET_KEY = os.environ.get('JWT_SECRET_KEY', 'your_super_secret_key_here')
async def homepage(request):
return JSONResponse({'hello': 'world'})
async def protected_route(request):
return JSONResponse({'data': 'This is protected data!'})
routes = [
Route('/', homepage),
Route('/protected', protected_route)
]
middleware = [
JWTAuth(
secret_key=SECRET_KEY,
# Exclude paths that don't require authentication
excluded_paths=['/', '/docs'],
# Allow an endpoint to create a token for testing
# In a real app, this would be a login endpoint
get_token_response=lambda user_id: JSONResponse({'token': f'fake-jwt-token-for-{user_id}'})
)
]
app = Starlette(routes=routes, middleware=middleware)
# To run this:
# uvicorn your_module_name:app --port 8000 --reload
# Access with: http://127.0.0.1:8000/
# Try http://127.0.0.1:8000/protected with a valid JWT in Authorization header
# You can use the get_token_response for generating a dummy token in dev.