Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple issues when using StrictUndefined in app.jinja_env.undefined #2522

Open
ddorian opened this issue Sep 11, 2024 · 1 comment
Open

Comments

@ddorian
Copy link

ddorian commented Sep 11, 2024

I like to use StrictUndefined to catch more errors in my templates. This raises many errors in flask-admin. You can simply check by enabling it in tests.

from jinja2 import StrictUndefined
app.jinja_env.undefined = StrictUndefined

Environment:

  • Python version:3.12
  • Flask version:3.0.3
  • Flask-Admin version:2.0.0a0

For now I'm using a custom class to ignore these (I configure all flask-admin blueprints to start with admin2):

class MyStrictUndefined(StrictUndefined):
    """Work like StrictUndefined except in flask-admin views/blueprints."""

    @property
    def is_admin2_blp(self) -> bool:
        if flask.request and flask.request.blueprint:
            return bool(flask.request.blueprint.startswith("admin2"))
        return False

    def __eq__(self, other: t.Any) -> bool:  # type: ignore[override]
        if self.is_admin2_blp:
            return type(self) is type(other)
        self._fail_with_undefined_error()

    def __ne__(self, other: t.Any) -> bool:  # type: ignore[override]
        if self.is_admin2_blp:
            return not self.__eq__(other)
        self._fail_with_undefined_error()

    #
    # def __hash__(self) -> int:
    #    return id(type(self))
    #
    # def __str__(self) -> str:
    #    return ""
    #
    # def __len__(self) -> int:
    #    return 0
    #
    # def __iter__(self) -> t.Iterator[t.Any]:
    #    yield from ()
    #
    # async def __aiter__(self) -> t.AsyncIterator[t.Any]:
    #    for _ in ():
    #        yield

    def __bool__(self) -> bool:  # type: ignore[override]
        if self.is_admin2_blp:
            return False
        self._fail_with_undefined_error()

    # def __repr__(self) -> str:
    #    return "Undefined"
@samuelhwilliams
Copy link
Contributor

Agree this would be nice to fix - would be very happy to accept a PR on this 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants