pybrake icon indicating copy to clipboard operation
pybrake copied to clipboard

Pybrake raises depecration warnings with the FastAPI middleware

Open pouellet opened this issue 1 year ago • 2 comments

Hi team,

Pybrake raises deprecation warnings when used with the FastAPI middleware:

pybrake/middleware/fastapi.py:1: DeprecationWarning: ExceptionMiddleware is deprecated on `starlette.exceptions`. Import it from `starlette.middleware.exceptions` instead.
    from .starlette import init_pybrake

pybrake/notifier.py:394: DeprecationWarning: Accessing attr.__version__ is deprecated and will be removed in a future release. Use importlib.metadata directly to query for attrs's packaging metadata.
    if hasattr(mod, "__version__"):

pybrake/notifier.py:395: DeprecationWarning: Accessing attr.__version__ is deprecated and will be removed in a future release. Use importlib.metadata directly to query for attrs's packaging metadata.
    versions[name] = mod.__version__

I am using the following versions:

Python 3.11.4

pybrake = "==1.10.1"
fastapi = "==0.100.0"
starlette = "==0.27.0"

pouellet avatar Aug 17 '23 23:08 pouellet

I'm getting the same thing. Any updates?

Maybe14 avatar Sep 26 '23 19:09 Maybe14

We can apply the patch like below to address this warning until pybrake provides a fix in future updates.

import importlib.metadata
import sys
from typing import Any, Dict

import pybrake.notifier


def get_version(name: str) -> str:
    """Get version using importlib.metadata."""
    return importlib.metadata.version(name)


def patched_build_context(self: Any) -> Dict[str, Any]:
    """Patched version of pybrake.notifier.Notifier._build_context."""
    ctx = self._context.copy()  # pylint: disable=W0212
    versions = ctx["versions"]

    for name, _ in sys.modules.items():
        if name.startswith("_"):
            continue
        try:
            # Use importlib.metadata.version to get the version of the module
            versions[name] = get_version(name)
        except importlib.metadata.PackageNotFoundError as exc:
            print(f"Failed to get version for {name}. Error: {str(exc)}")
            versions[name] = None

    return ctx


def apply_pybrake_patch() -> None:
    """Apply the monkey patch to the pybrake.notifier module."""
    pybrake.notifier.Notifier._build_context = patched_build_context  # pylint: disable=W0212

alokRamteke avatar Aug 08 '24 12:08 alokRamteke