Repository navigation
refactor(config): deprecate config.foca accessors - #721
Conversation
get_config() and get_custom_config() are the only supported ways to read the configuration in apps. Reading or setting app.config.foca and calling get_app_config() now emit a DeprecationWarning and keep working: the configuration stays where it was, and the class of the app's Flask configuration gets a property that warns. FOCA's own reads use get_config() or, where the app is known but not current (while it is created), a private helper without the warning. Tests, the gateway example, the configuration docs and the migration guide follow. Closes #716 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Read the configuration without the warning also where FOCA registers APIs (error media type, rejection of invalid tokens), which looked it up with getattr(). Let deleting app.config.foca work, deprecated, and pickle Flask configurations as their original class. Attach the configurations of test apps with set_app_config(), and show how to read that of an app that isn't the current one in the migration guide. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rewrite only the reductions of copyreg (and those naming the subclass itself) when pickling a Flask configuration as its original class, so that configuration classes with their own __reduce__() keep working, also with keyword arguments of __new__() and globals. Note in the migration guide that the class of app.config is a subclass while the attribute is deprecated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThe PR deprecates direct Sequence diagram for deprecated configuration accesssequenceDiagram
participant App as FlaskApp
participant Config as AppConfig
participant Access as foca.config.access
participant Caller
App->>Access: set_app_config(app, config)
Access->>Config: vars(config)[foca] = config
Access->>Config: _deprecate_attribute(app)
Access-->>App: Dynamic config subclass installed
Caller->>Config: app.config.foca
Config->>Access: _get_foca_attribute(config)
Access-->>Caller: DeprecationWarning + configuration
Caller->>Access: get_app_config(app)
Access-->>Caller: DeprecationWarning + _get_app_config(app)
Flow diagram for supported configuration accessflowchart LR
AppContext[App context] --> GetConfig["get_config()"]
GetConfig --> CurrentConfig[Current app configuration]
NoAppContext[No app context] --> GetConfig
GetConfig --> LatestConfig[Most recently created FOCA app]
KnownApp[Known non-current app] --> PrivateLookup["_get_app_config(app)"]
CurrentConfig --> Custom["get_custom_config()"]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #721 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 71 71
Lines 9066 9099 +33
=========================================
+ Hits 9066 9099 +33
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/config/access.py" line_range="180" />
<code_context>
+ return
+ with _deprecating_classes_lock:
+ if cls not in _deprecating_classes:
+ _deprecating_classes[cls] = type(
+ cls.__name__,
+ (cls,),
</code_context>
<issue_to_address>
**Custom config metaclass breaks app creation**
When an app uses a Flask config class with a custom metaclass, `type(...)` constructs the wrapper with the built-in metaclass instead of the config class’s metaclass. For a config class whose metaclass is not compatible with `type`, class creation raises `TypeError`, so attaching the FOCA config fails.
Create the wrapper using the config class’s metaclass, or use another approach that preserves custom metaclasses.
</issue_to_address>
### Comment 2
<location path="foca/config/access.py" line_range="180-194" />
<code_context>
+ return
+ with _deprecating_classes_lock:
+ if cls not in _deprecating_classes:
+ _deprecating_classes[cls] = type(
+ cls.__name__,
+ (cls,),
+ {
+ "__module__": cls.__module__,
+ "__qualname__": cls.__qualname__,
+ "__reduce_ex__": _reduce_ex,
+ _DEPRECATING_MARKER: True,
+ _ATTRIBUTE: property(
+ _get_foca_attribute,
+ _set_foca_attribute,
+ _delete_foca_attribute,
+ ),
+ },
+ )
+ app.config.__class__ = _deprecating_classes[cls]
+
</code_context>
<issue_to_address>
**Custom config apps fail at setup**
When an app uses a custom Flask config class with a required-keyword `__init_subclass__` hook, `type()` creates the warning subclass without forwarding any class keywords, so a custom Flask config class whose `__init_subclass__` requires a keyword raises `TypeError` and `set_app_config()` aborts app creation.
Provide a way to create the warning subclass for custom config classes whose subclass hooks require arguments, or avoid making app creation depend on subclassing them.
</issue_to_address>
### Comment 3
<location path="foca/config/access.py" line_range="177" />
<code_context>
+ """
+ cls = type(app.config)
+ if getattr(cls, _DEPRECATING_MARKER, False):
+ return
+ with _deprecating_classes_lock:
+ if cls not in _deprecating_classes:
</code_context>
<issue_to_address>
**Inherited config classes fail pickling**
When an app uses a Flask config class derived from the runtime class of a previously wrapped app config, `_deprecate_attribute` sees the inherited marker through `getattr` and skips wrapping the child; its inherited `_reduce_ex` then treats the generated class as the original or recurses through `super(Child, instance)`, so pickling raises `PicklingError` or `RecursionError`.
Skip wrapping only when the marker is defined directly on the config class, not inherited.
Also at `foca/config/access.py:113`.
</issue_to_address>
### Comment 4
<location path="foca/config/access.py" line_range="130" />
<code_context>
+ original = cls.__mro__[1]
+ reduced = super(cls, flask_config).__reduce_ex__(protocol)
+ if isinstance(reduced, str):
+ return reduced
+ function, args, *rest = cast("tuple[Any, ...]", reduced)
+ # E.g., `__reduce__()` returning `type(self)` and its arguments
</code_context>
<issue_to_address>
**Custom config reducers fail pickling**
When a custom Flask config class returns a reduction whose arguments include `type(self)` and whose callable is not the class itself or one of the handled `copyreg` functions, `_reduce_ex` returns the reduction unchanged, leaving the generated wrapper class in the factory arguments; pickle cannot resolve that synthetic class through its original module and qualified name, so serializing the config raises `PicklingError`.
Replace the generated wrapper class with the original config class in the custom reduction’s arguments.
</issue_to_address>
### Comment 5
<location path="foca/config/access.py" line_range="35" />
<code_context>
+
+# Subclasses of Flask configuration classes with the deprecated attribute, by
+# class
+_deprecating_classes: dict[type[FlaskConfig], type[FlaskConfig]] = {}
+_deprecating_classes_lock = threading.Lock()
+
</code_context>
<issue_to_address>
**Discarded config classes remain in memory**
When apps are repeatedly created and discarded with distinct dynamically generated config classes, `_deprecating_classes` strongly retains each original config class and its generated subclass, so their classes and associated definitions remain alive and process memory grows.
Avoid retaining original and generated config classes in a module-level strong-reference cache.
Also at `foca/config/access.py:179`.
</issue_to_address>Linked issues
#716 refactor(config): deprecate config.foca accessors · 3 of 3 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Deprecate current_app.config.foca and get_app_config(flask_app) with a DeprecationWarning. |
✅ Met | Reads and writes of the Flask config attribute warn, and the public get_app_config() warns; both continue to work. |
| 2 | Switch FOCA's internal uses to get_config(). |
✅ Met | FOCA uses get_config() for current-app access and the private _get_app_config() where it must retrieve a known, possibly non-current app's config; internal code no longer uses the deprecated public accessor or reads config.foca. |
| 3 | Note the deprecation in docs/migration-0.22.md. |
✅ Met | The new “Configuration access” section lists the deprecated forms, replacements, and migration guidance. |
Sourcery assessment
Approval pending. 5 findings to address first.
Blocking findings: foca/config/access.py:180, foca/config/access.py:194, foca/config/access.py:177, foca/config/access.py:130, foca/config/access.py:35
Give only Flask configurations of Flask's own class, as Connexion creates them, a static subclass whose attribute foca warns, instead of creating a subclass of any configuration class at runtime: those broke custom metaclasses, __init_subclass__ hooks, reductions and inheritance in corner cases, and were kept in memory. Apps with configuration classes of their own keep them, without the warning. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-config-foca # Conflicts: # docs/migration-0.22.md
Summary
As decided in #634,
get_config()andget_custom_config()are the only supported ways to read the configuration in apps. This deprecates the other two, which keep working until the first release candidate on ASGI:app.config.foca/current_app.config.foca: reading, setting and deleting it emits aDeprecationWarning. The configuration stays where it was (the Flask config's instance attribute);set_app_config()swaps Flask configurations of Flask's own class, as Connexion creates them, to a static subclass whosefocaproperty warns. A config class can't do this, as Connexion createsapp.configbefore FOCA attaches its configuration. Apps with a configuration class of their own keep it, without the warning ("where FOCA can emit one").foca.config.access.get_app_config(app)emits aDeprecationWarning.FOCA's own reads use
get_config(), or, where the app is known but not current (while it is created, in the Celery factory,require_no_service_clients(app), API registration), the private_get_app_config()/_find_app_config()without the warning. FOCA's tests, the gateway example, "Accessing the configuration" (docs/configuration/index.md) anddocs/migration-0.22.md(new section "Configuration access", with a before/after example for apps that aren't the current one) follow.Closes #716
Verification
coverage run -m pytestwith MongoDB 7.0, with these deprecations turned into errors (-W "error:'app.config.foca' is deprecated:DeprecationWarning", likewise for setting, deleting andget_app_config()): 4622 passed, 2 skipped, 100% coverage, so FOCA itself no longer uses themruff check,ruff format --check,mypy,ast-grep scan,semgrep scan --config .semgrep --error,mkdocs build --strict: passhelm dependency build deploymentwith Helm 3.22.1, as CI). Both use the deprecated accessors only in their tests, with Flask's own config class, so they warn the same with the final design (c86e81a only changes how the warning is installed); their CI runspytest -W ignore::DeprecationWarning, so nothing fails, and their app code uses neither:dev(4e707a9): mongomock with coverage (deprecation warnings not ignored): 2337 passed, 11 skipped, 100% coverage; against MongoDB 7.0: 2348 passed.get_app_config()warns at 7 places in its tests:tests/conftest.py:440,tests/test_app.py:159,:638,:1108,:2444,tests/test_exceptions.py:35,tests/ga4gh/registry/test_service_info.py:114.dev(e47cac2): mongomock with coverage (deprecation warnings not ignored): 1613 passed, 11 skipped, 100% coverage; against MongoDB 7.0: 1623 passed.app.config.focawarns attests/test_gateway.py:44.Declined review findings
_get_app_config()/_find_app_config()imported across modules and in tests: the codebase's convention for internal helpers (e.g.,_match_rule,_normalize_resolver,_redact), and they mustn't become public API next to the deprecated one.get_config()falls back to outside app contexts: unchanged from before, whenapp.config.focawas a plain attribute.ownership_serverreadsserver.public_urlwithget_config()(falls back to the latest app if the current one has no FOCA configuration) instead of raising: as the issue asks; within requests to a FOCA app, the current app always has its configuration.type(app.config)for apps with Flask's own config class: noted in the migration guide;isinstance(app.config, flask.Config)still holds.Sourcery's findings on the earlier design (per-class subclasses created at runtime: custom metaclasses,
__init_subclass__hooks, custom reductions, inherited markers, memory) are fixed by the static subclass.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Migrate application configuration access to
get_config()andget_custom_config()while warning on legacy accessors ahead of their removal.Enhancements:
app.config.focaandget_app_config()in favor of the supported typed configuration accessors.Documentation:
Tests: