Skip to main content

PG-DB

PG-DB is simple Psycopg wrapper.

Usage

First create an DB object and initialise it with the application,

from pg_db import DB

db = DB('test', 'root', debug=True)

def set_user(name):
    db.connect()
    db.execute("INSERT INTO users VALUES('Wendys');", (name, ))
    db.commit()
    db.close()

set_user('xyz')

can select one row,

def get_user(id):
    db.connect()
    row = db.one("SELECT name FROM users WHERE id=%s", (id, ), as_dict=True)
    db.close()
    return row['name']

print(get_user(1))

can select all rows,

def get_users():
    db.connect()
    rows = db.all("SELECT name FROM users;")
    db.close()
    return rows

print(get_users())

Usage on Quart

First create a Quart wrapper file (db.py),

from functools import wraps
from pg_db import DB
from quart import flash, redirect, request, session, url_for  # make_response
from quart_auth import current_user

class db(DB):
  def wrapper(self, func):
    @wraps(func)
    async def wrapped(*args, **kwargs):
      try:
        self.connect(session['schema'] if 'schema' in session else 'public',
                     'QUART_AUTH' in request.cookies and await current_user.readonly)
        return await func(*args, **kwargs)
      except Exception as e:
        self.rollback()
        if self.debug:
          raise e
        await flash("db error -> " + str(e))
        return redirect(url_for(request.endpoint))
        # return await make_response("db error -> " + str(e), 500)
      finally:
        try:
          self.close()
        except:
          pass
    return wrapped

Then enable db object from db.py globally for a Quart app,

from json import dumps
from .db import db

app = Quart(__name__)
db = db(AppConfig.DB_NAME, AppConfig.DB_USER, AppConfig.DEBUG)

@app.route('/get_users')
@db.wrapper
async def get_users():
    return dumps(db.all("SELECT name FROM users;"))

Usage on Flask

First create a Flask wrapper file (db.py),

from functools import wraps
from pg_db import DB
from flask import flash, redirect, request, session, url_for  # make_response
from flask_login import current_user

class db(DB):
  def wrapper(self, func):
    @wraps(func)
    def wrapped(*args, **kwargs):
      try:
        self.connect(session['schema'] if 'schema' in session else 'public',
                     current_user.is_authenticated and current_user.readonly)
        return func(*args, **kwargs)
      except Exception as e:
        self.rollback()
        if self.debug:
          raise e
        flash("db error -> " + str(e))
        return redirect(url_for(request.endpoint))
        # return make_response("db error -> " + str(e), 500)
      finally:
        try:
          self.close()
        except:
          pass
    return wrapped

Then enable db object from db.py globally for a Flask app,

from json import dumps
from .db import db

app = Flask(__name__)
db = db(AppConfig.DB_NAME, AppConfig.DB_USER, AppConfig.DEBUG)

@app.route('/get_users')
@db.wrapper
def get_users():
    return dumps(db.all("SELECT name FROM users;"))

Contributing

PG-DB is developed on GitLab. You are very welcome to open issues or propose merge requests.

Help

This README is the best place to start, after that try opening an issue.

Metadata

Release files for pg-db 1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pg-db 1.2
File Size Uploaded Provenance
pg-db-1.2.tar.gz 15.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for pg-db 1.2
File Interpreter ABI Platform
pg_db-1.2-py3-none-any.whl Python 3 none any Details

Total release size: 31.1 kB

Release files / pg-db-1.2.tar.gz

Download URL pg-db-1.2.tar.gz
Size 15.5 kB
Tags Source
SHA-256 checksum
How to use checksums
a33b036c207e0126b8d2cad8264716350922f304381985968ba6622f5b2f1815
BLAKE2b-256 checksum
How to use checksums
37ebb9fa9b27dbdb245c40752b09c64a3c2896e7261b5f0cf7dc20ea7121ff82
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.2

Release files / pg_db-1.2-py3-none-any.whl

Download URL pg_db-1.2-py3-none-any.whl
Size 15.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e9727117bbd07708bbc2915eac974ee7465f837e870c6ee0df2bc83e0b6c5549
BLAKE2b-256 checksum
How to use checksums
a5cf4d44b14bbb9a0b2348a21be4358add87cdd57dc483a3efbc37cefce4cc3b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.2

Security for pg-db 1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page