encode / django-rest-framework

Web APIs for Django. 🎸
https://www.django-rest-framework.org
Other
27.83k stars 6.76k forks source link

Added protections to AttributeErrors raised within properties #9455

Open james-mchugh opened 5 days ago

james-mchugh commented 5 days ago

Description of Changes

Creates a safe_property decorator in request.py that utilizes the wrap_attributeerrors context manager to ensure all properties in the Request class properly handle any AttributeErrors raised internally.

Updates the __getattr__ function to explicitly raise an AttributeError rather than calling __getattribute__ again, as calling __getattribute__ can have unexpected side effects (see #9433).

Adds a unit test to cover the case where a Parser raises an attribute error when the Request.data property is accessed.

Benefits

AttributeErrors raised in properties such as from parsing will now produce sane error messages and will no longer result in errors being suppressed.

Possible drawbacks

None that I am currently aware of.

Applicable issues

Additional information

There appears to already be a precedent for this type of handling in request.py with the wrap_attributeerrors context manager that is currently only used for authentication. This extends that behavior to other properties via a common safe_property decorator that can be used instead of the builtin property decorator.

While I think adding a decorator such as safe_property that utilizes wrape_attributeerrors is an elegant way of handling this, I'm also open to just adding the wrap_attributeerrors context manager wherever needed.