safir.slack.webhook.SlackWebhookClientand accompanying models to post a structured message to Slack via an incoming webhook. Add a
safir.slack.blockkit.SlackExceptionbase class that can be used to create exceptions with supplemental metadata that can be sent to Slack as a formatted alert.
Add a FastAPI route class (
safir.slack.webhook.SlackRouteErrorHandler) that reports all uncaught exceptions to Slack using an incoming webhook.
safir.datetime.format_datetime_for_loggingto convert a
datetimeobject into an easily human-readable representation.
safir.testing.slack.mock_slack_webhookand an associated mock class to mock a Slack webhook for testing.
safir.datetime.current_datetimeto get a
datetimeobject with microseconds filled in. By default,
current_datetimesuppresses the microseconds since databases often cannot store them, but there are some timestamp uses, such as error reporting, that benefit from microseconds and are never stored in databases.
safir.testing.uvicorn.spawn_uvicornhelper function to spawn an ASGI app under an external Uvicorn process. Normally, ASGI apps should be tested by passing the app directly to an
httpx.AsyncClient, but in some cases (such as Selenium testing) the app needs to listen to regular HTTP requests.
safir.database.initialize_databasenow creates a non-default schema if the underlying SQLAlchemy model declares one.
safir.logging.configure_uvicorn_loggingwas called, exception tracebacks were no longer expanded. Add the missing processor to the logging stack.
safir.logging.configure_uvicorn_logging, send the access log to standard output instead of combining it with all other messages on standard error.
safir.models.ErrorLocationenum holding valid values for the first element of the
safir.models.ErrorModel. Due to limitations in Python typing,
locis not type-checked against this enum, but it may be useful to applications constructing FastAPI-compatible error messages.
safir.datetime.current_datetimeto get a normalized
datetimeobject representing the current date and time.
safir.datetime.parse_isodatetimeto convert to and from the most useful form of ISO 8601 dates, used by both Kubernetes and the IVOA UWS standard. Also add
safir.pydantic.normalize_isodatetimeto accept only that same format as input to a Pydantic model with a
Add new helper class
safir.gcs.SignedURLServiceto generate signed URLs to Google Cloud Storage objects using workload identity. To use this class, depend on
safir.testing.gcsmodule, which can be used to mock the Google Cloud Storage API for testing. To use this module, depend on
Add new helper class
safir.pydantic.CamelCaseModel, which is identical to
pydantic.BaseModelexcept with configuration added to accept camel-case keys using the
safir.pydantic.to_camel_casealias generator and overrides of
jsonto export in camel-case by default.
LogLevelenums in addition to strings for the
log_levelparameters. The new enums are preferred. Support for enums was added in preparation for changing the FastAPI template to use
Configurationclass and validate the values of the
Add new function
safir.pydantic.normalize_datetime, which can be used as a Pydantic validator for
datetimefields. It also allows seconds since epoch as input, and ensures that the resulting
datetimefield in the model is timezone-aware and in UTC.
Add new function
safir.pydantic.to_camel_case, which can be used as a Pydantic alias generator when a model needs to accept attributes with camel-case names.
Add new function
safir.pydantic.validate_exactly_one_of, which can be used as a model validator to ensure that exactly one of a list of fields was set to a value other than
safir.testing.kubernetes.patch_kubernetes, correctly apply a spec to the mock of
kubernetes_asyncio.client.ApiClient. Due to an ordering bug in previous versions, the spec was previously a mock object that didn’t apply any constraints.
Add new function
safir.logging.configure_uvicorn_loggingthat routes Uvicorn logging through structlog for consistent formatting. It also adds context to Uvicorn logs in the format recognized by Google’s Cloud Logging.
Support the newer project metadata structure and URL naming used by
pyproject.toml-only packages in
New support for arq, the Redis-based asyncio distributed queue package. The
safir.arqmodule provides an arq client and metadata/result data classes with a mock implementation for testing. The FastAPI dependency,
safir.dependencies.arq.arq_dependency, provides a convenient way to use the arq client from HTTP handlers.
Add new FastAPI middleware
CaseInsensitiveQueryMiddlewareto aid in implementing the IVOA protocol requirement that the keys of query parameters be case-insensitive.
Correctly handle the possibility that
Fix handling of passwords containing special characters such as
safir.databaseretains the port in the database URL, if provided.
XForwardedMiddlewareno longer sets
forwarded_protoin the request state and instead directly updates the request scope so that subsequent handlers and middleware believe the request scheme is that given by an
X-Forwarded-Protoheader. This fixes the scheme returned by other request methods and attributes such as
url_forin cases where the service is behind an ingress that terminates TLS.
Add new FastAPI dependencies
auth_dependencyreturns the username of the user authenticated via Gafaelfawr (pulled from the
auth_logger_dependencyreturns the same logger as
logger_dependencybut with the
userparameter bound to the username from
Add utility functions to initialize a database and create a sync or async session. The session creation functions optionally support a health check to ensure the database schema has been initialized.
Add new FastAPI dependency
db_session_dependencythat creates a task-local async SQLAlchemy session.
Add utility functions
datetime_to_dbto convert between timezone-naive UTC datetimes stored in a database and timezone-aware UTC datetimes used elsewhere in a program.
run_with_asyncdecorator that runs the decorated async function synchronously. This is primarily useful for decorating Click command functions (for a command-line interface) that need to make async calls.
Add a very basic and limited implementation of
In the Kubernetes mock API, change the expected body for
patch_namespaced_custom_object_statusto reflect the need to send a JSON patch for the entirety of the
/statuspath in order to work around a kubernetes_asyncio bug.
initialize_kuberneteshelper function to load Kubernetes configuration. Add the
safir.testing.kubernetesmodule, which can be used to mock the Kubernetes API for testing. To use the new Kubernetes support, depend on
When logging in JSON format, use
levelfor the log level for compatibility with Google Log Explorer.
In the FastAPI
logger_dependency, add log information about the incoming requst in a format compatible with Google Log Explorer.
http_client_dependencybehavior by enabling following redirects by default. This adjusts for the change of defaults in httpx 0.20.0.
Require structlog 21.2.0 and adjust logger configuration of exception handling for the expectations of that version.
safir.models.ErrorModel, which is a model of the error message format preferred by FastAPI. Using the model is not necessary but it’s helpful to reference it in API documentation to generate more complete information about the error messages.
Mark all FastAPI dependencies as async so that FastAPI doesn’t run them in an external thread pool.
Defer creation of
httpx.AsyncClientuntil the first time it is requested. Allow re-creation after
aclose(), which makes it easier to write test suites.
As of this release, Safir is a helper library for FastAPI applications instead of aiohttp applications. Much of the library has changed. Authors of software that uses Safir should read the documentation again as part of the upgrade to FastAPI.
Included in this release is:
A FastAPI dependency to provide a structlog logger as configured by the
safir.loggingpackage, replacing the aiohttp middleware.
A FastAPI dependency to provide a global
httpx.AsyncClient, replacing the middleware that provided an aiohttp client.
Starlette (FastAPI) middleware to parse
X-Forwarded-*headers and update request information accordingly.
safir.metadata.get_metadatanow returns a Pydantic model.
As of this release, Safir only supports Python 3.8 or later.
Safir v1 will be the major release supporting aiohttp. Starting with Safir v2, Safir will become a support library for FastAPI applications.
This release has no significant difference from 0.2.0. The version bump is to indicate that the aiohttp support is stable.
configure_loggingnow supports an optional
add_timestampparameter (false by default) that adds a timestamp to each log message.
Fix duplicated log output when logging is configured multiple times.
The first release of Safir featuring:
safir.httpfor adding an
aiohttp.ClientSessionto your application.
safir.loggingfor configuring structlog loggers.
safir.metadatahelps your gather and structure metadata about your application for publishing on metadata endpoints.
safir.middlewareincludes a logging middleware that adds a logger with bound context about the request to your Request object.
Documentation about these features and a tutorial for starting a new application with the