close
Skip to content

str(v) in core_enforcer.enforce_ex() is done even when not needed resulting in unnecessary code execution and DB calls #420

@manisar2

Description

@manisar2

Ask

Use str on rvals only if needed (for logging).

Detail

In core_enforcer.py, we have this here - note the [str(v) for v in rvals] in the second line:

        req_str = "Request: "
        req_str = req_str + ", ".join([str(v) for v in rvals])

        req_str = req_str + " ---> %s" % result
        if result:
            self.logger.info(req_str)
        else:
            # leaving this in warning for now, if it's very noise this can be changed to info or debug,
            # or change the log level
            self.logger.warning(req_str)

Our code passes Django model instances as rvals which have custom __str__s.
str(v) above causes the custom __str__s to be called which in turn result in DB calls we are trying to avoid.

We don't need INFO or WARNING level logging, so we have set the log level as error.
Thus we avoid the full logging block above, but in spite of that, the str(v) calls result in unnecessary DB calls - even though the req_str created is not used anywhere.

Suggestion

This altered code (or something similar) can make this block of code more efficient - as str on rvals will only be called if needed for logging.

        req_str = "Request: "

        if result and self.logger.level <=  logging.INFO:
            req_str = req_str + ", ".join([str(v) for v in rvals])
            req_str = req_str + " ---> %s" % result
            self.logger.info(req_str)

        elif self.logger.level <=  logging.WARNING:
            req_str = req_str + ", ".join([str(v) for v in rvals])
            req_str = req_str + " ---> %s" % result
            # leaving this in warning for now, if it's very noise this can be changed to info or debug,
            # or change the log level
            self.logger.warning(req_str)

Metadata

Metadata

Labels

enhancementNew feature or request

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions