korfuri / django-prometheus

Export Django monitoring metrics for Prometheus.io
Apache License 2.0
1.47k stars 245 forks source link

Support for Django 4.2 and Psycopg3 #350

Closed mounirmesselmeni closed 1 year ago

mounirmesselmeni commented 1 year ago

When using Django 4.2 with psycopg3, django-prometheus will break because of directly importing psycopg2

import psycopg2.extensions
ModuleNotFoundError: No module named 'psycopg2'
BeryJu commented 1 year ago

Creating a custom database backend based on the one provided by this library should work for both psycopg2 and 3:

"""Database engine that uses prometheus exporter"""
from django.db.backends.postgresql import base
from django_prometheus.db.common import DatabaseWrapperMixin, ExportingCursorWrapper

class DatabaseFeatures(base.DatabaseFeatures):
    """Our database has the exact same features as the base one."""

    pass

class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseWrapper):
    def get_connection_params(self):
        conn_params = super().get_connection_params()
        conn_params["cursor_factory"] = ExportingCursorWrapper(base.Cursor, self.alias, self.vendor)
        return conn_params

    def create_cursor(self, name=None):
        # cursor_factory is a kwarg to connect() so restore create_cursor()'s
        # default behavior
        return base.DatabaseWrapper.create_cursor(self, name=name)

(Remember to put that into a file named base.py into a module, and then set the ENGINE setting to the module import path)

lociii commented 1 year ago

@BeryJu would you mind adding a PR for the shipped postgresql and postgis backends? Would be great if everyone can profit from your findings. Thanks.

ekampf commented 1 year ago

As the PR to support hi is merged, any plans to release a new version to Pypi soon?

asherf commented 1 year ago

https://pypi.org/project/django-prometheus/2.3.0/

asherf commented 1 year ago

2.3.0 is broken so I yanked it. https://pypi.org/project/django-prometheus/2.3.1/ is available.