Skip to content

Fix #561#666

Merged
RobertoPrevato merged 5 commits intomainfrom
fix/561
Feb 24, 2026
Merged

Fix #561#666
RobertoPrevato merged 5 commits intomainfrom
fix/561

Conversation

@RobertoPrevato
Copy link
Member

@RobertoPrevato RobertoPrevato commented Feb 24, 2026

Support for baked OpenAPI Specification files (PYTHONOPTIMIZE=2 / -OO)

BlackSheep can enrich OpenAPI Documentation by parsing request handler docstrings. This does not work when Python runs with PYTHONOPTIMIZE=2 (or -OO), because docstrings are stripped at that level of optimisation.

This PR adds a first-class solution: the ability to bake the OpenAPI spec to disk at build/CI time and load it at runtime instead of regenerating it.

Changes

OpenAPIHandler.save_spec(destination)
Writes the current in-memory spec to disk. Both the JSON and YAML variants are always written, regardless of which extension is given. Intended to be called once — in a CI step or a dedicated bake script — after the application has started without -OO.

spec_file= constructor parameter on OpenAPIHandler
When set, build_docs loads the pre-baked spec from disk instead of calling generate_documentation. If the files are missing on first startup, the spec is generated, saved automatically, and loaded from disk on every subsequent startup (first-startup auto-bake).

APP_SPEC_FILE environment variable
An alternative to spec_file= that requires no code change between environments. Set it in TEST / PROD to activate the baked-spec path; leave it unset in development to keep auto-generation.

PYTHONOPTIMIZE=2 warning in docstring parsing
When Python runs with optimize >= 2 and a request handler has no docstring, a single UserWarning is issued at startup advising the user to bake the spec file.

Workflow

# bake_spec.py — run once in CI, without -OO
import asyncio
from myapp import app, docs

asyncio.run(app.start())
docs.save_spec("./openapi.json")  # also writes ./openapi.yaml
# In TEST / PROD — no application code change needed
export APP_SPEC_FILE=./openapi.json

On the first deployment startup (files not yet present) the spec is generated and saved automatically. From the second startup onward it is read directly from disk, skipping generation entirely — which also improves startup time for large APIs.

@RobertoPrevato RobertoPrevato merged commit b855ed1 into main Feb 24, 2026
16 checks passed
@RobertoPrevato RobertoPrevato deleted the fix/561 branch February 24, 2026 06:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant