Skip to main content

Versioning and auditing extension for PostgreSQL and SQLAlchemy.

Project description

Flask-PostgreSQL-Audit

BuildStatus VersionStatus

Auditing extension for Flask-SQLAlchemy with PostgreSQL. Forked from PostgreSQL-Audit, tries to combine the best of breed from existing solutions such as SQLAlchemy-Continuum, Papertrail and especially Audit Trigger by 2ndQuadrant.

  • Stores audit recordss into single table called pga_activity
  • Uses trigger based approach to keep INSERTs, UPDATEs and DELETEs as fast as possible
  • Tracks and stores actor identities into table called pga_transaction
  • Uses Alembic and Alembic-Utils to generate necessary database objects for migration

Installation

pip install flask-postgresql-audit

or using uv

uv add flask-postgresql-audit

or install directly from this repo

uv add git+https://github.com/higamigu/flask-postgresql-audit --tag v1.0.0

Usage

from flask_sqlalchemy import SQLAlchemy
from flask_postgresql_audit import PostgreSQLAudit, Audit

from my_app import app  # your flask app

db = SQLAlchemy()
audit = PostgreSQLAudit()

class Article(db.Model, Audit):
    __tablename__ = 'article'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

db.init_app(app)
audit.init_app(app, db)

article = Article(name='Some article')
db.session.add(article)
db.session.commit()

Then generate migration file

flask db migrate -m "pg audit initial migration"
flask db upgrade

Now we can check the newly created activity.

activity = db.session.scalar(select(audit.Activity))
activity.id             # 1
activity.table_name     # 'article'
activity.verb           # 'insert'
activity.old_data       # None
activity.changed_data   # {'id': '1', 'name': 'Some article'}
article.name = 'Some other article'
db.session.commit()

activity = db.session.scalar(select(audit.Activity).order_by(desc("id")))
activity.id             # 2
activity.table_name     # 'article'
activity.verb           # 'update'
activity.object_id      # 1
activity.old_data       # {'id': '1', 'name': 'Some article'}
activity.changed_data   # {'name': 'Some other article'}
db.session.delete(article)
db.session.commit()

activity = db.session.scalar(select(audit.Activity).order_by(desc("id")))
activity.id             # 3
activity.table_name     # 'article'
activity.verb           # 'delete'
activity.object_id      # 1
activity.old_data       # {'id': '1', 'name': 'Some other article'}
activity.changed_data   # None

Different Schema

You can isolate pg_audit objects entirely to a different schema by doing

from flask_postgresql_audit import PostgreSQLAudit

audit = PostgreSQLAudit(schema="audit")

...

And then you need to tell alembic to track other than public schema by adding following line in alembic/env.py

...

def run_migrations_online():
    connectable = get_engine()

    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=get_metadata(),
            include_schemas=True, # add this arg
            ...
        )

        with context.begin_transaction():
            context.run_migrations()

...

Custom Actor ID getter

You can customize actor id getter function by doing the following. Here is an example using current_user from flask_jwt_extended library.

from flask_jwt_extended import jwt_required, current_user

@jwt_required(optional=True)
def actor_id_getter():
    try:
        return current_user.email or None
    except Exception:
        return None

...

audit = PostgreSQLAudit(actor_id_getter=actor_id_getter)

...

Enable Alembic Logger

You can enable alembic logger for pg_audit by adding the following to your alembic.ini

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic,alembic_utils,pg_audit # add 'pg_audit' here

...

[logger_pg_audit]  # and add the logger for pg_audit here
level = INFO
handlers =
qualname = pg_audit

Running the tests

git clone https://github.com/higamigu/flask-postgresql-audit.git
cd flask-postgresql-audit
pip install tox
createdb postgresql_audit_test
tox

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask_postgresql_audit-1.0.6.tar.gz (23.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flask_postgresql_audit-1.0.6-py3-none-any.whl (25.3 kB view details)

Uploaded Python 3

File details

Details for the file flask_postgresql_audit-1.0.6.tar.gz.

File metadata

  • Download URL: flask_postgresql_audit-1.0.6.tar.gz
  • Upload date:
  • Size: 23.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for flask_postgresql_audit-1.0.6.tar.gz
Algorithm Hash digest
SHA256 e5aa91b138aaca30a3168efb99af6edca11975b3e62924ebe337e1f6c449d006
MD5 81d14077b10a2b62728d6ea15742fd47
BLAKE2b-256 e0bdbe4975058e49f82decb52cca37047c61a04a8e6f2dc467a4ed663f42f192

See more details on using hashes here.

File details

Details for the file flask_postgresql_audit-1.0.6-py3-none-any.whl.

File metadata

File hashes

Hashes for flask_postgresql_audit-1.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 02741dbcbea4f942e9581dadb626ce8e7c218cd3da892c4475313bd919b9fb87
MD5 4abea1838ff6dc01e109448d6f6c5791
BLAKE2b-256 a1e9926a471de0ef72185cafea068ef4351d89778f4b16ea2aed83179ab9e57f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page